xamarin - 我是否需要停止在 UI 线程中运行的方法?

标签 xamarin xamarin.forms

我的应用程序如下所示:

应用程序类别:

protected override void OnStart()
{
   MainPage = new Japanese.MainPage();
}

主页类:

var phrasesPage = new NavigationPage(new PhrasesPage())
{
   Title = "Play",
   Icon = "play.png"
};
Children.Add(phrasesPage);

短语页面类:

protected override void OnAppearing()
{
   base.OnAppearing();
   phrasesFrame = new PhrasesFrame(this);
   phrasesStackLayout.Children.Add(phrasesFrame);
}

protected override void OnDisappearing()
{
   base.OnDisappearing();
   phrasesStackLayout.Children.Remove(phrasesFrame);
}

PhrasesFrame 类:

public PhrasesFrame(PhrasesPage phrasesPage)
{
   InitializeComponent();
   Device.BeginInvokeOnMainThread(() => ShowCards().ContinueWith((arg) => { }));
}

public async Task ShowCards()
{
   while (true)
   {
      // information displayed on screen here and screen
      // responds to user clicks
      await Task.Delay(1000);
    }
}

这里有两个问题。

首先,我的 ShowCards 方法没有返回,因为它会循环,直到用户单击屏幕底部的另一个图标来选择另一个屏幕。在这种情况下,我应该为返回值编写什么代码。因为 IDE 会警告方法永远不会到达末尾或返回语句。我该如何解决这个问题。

第二个相关问题。由于 ShowCards 在另一个线程上运行,当用户单击另一个图标以显示另一个屏幕时,我是否应该执行某些操作来取消它。

希望有人能帮我提点建议。如果有不清楚的地方请询问,以便我可以尝试使问题更清楚。谢谢

最佳答案

IDE 警告您该方法永远不会到达末尾,因为它确实永远不会到达末尾,并且正如所写,您的任务将永远运行(或至少直到应用程序关闭)。

允许中断正在运行的任务的标准方法是提供 CancellationToken当您创建任务时。您从 CancellationTokenSource 获取 token ,将 token 提供给任务,然后调用 CancellationTokenSource 上的 Cancel()CancellationToken.IsCancellationRequested 属性设置为 true,表示它应该结束的任务。

在你的情况下,你可以有这样的东西:

CancellationTokenSource cts new CancellationTokenSource();

public PhrasesFrame(PhrasesPage phrasesPage)
{
   InitializeComponent();
   Device.BeginInvokeOnMainThread(() => ShowCards(cts.Token).ContinueWith((arg) => { }));
}

public Disappearing() {
    cts.Cancel();
}

public async Task ShowCards(CancellationToken ct)
{
   while (!ct.IsCancellationRequested)
   {
      // information displayed on screen here and screen
      // responds to user clicks
      await Task.Delay(1000, ct);
    }
}

然后当您希望结束任务时调用 Disappearing(),例如在 PhrasesPage 方法中:

protected override void OnDisappearing()
{
   base.OnDisappearing();
   phrasesFrame.Disappearing();
   phrasesStackLayout.Children.Remove(phrasesFrame);
}

关于xamarin - 我是否需要停止在 UI 线程中运行的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238066/

相关文章:

android - 在 Xamarin 中,我需要在 map 中心设置标记并获取位置

xamarin.forms - Xamarin 表单检查键盘是否打开

c# - 在 Xamarin 中设置窗口 KeepScreenOn 标志

android - 在 Xamarin 中获取电话状态

c# - 动态 HeightRequest 不适用于 StackLayout

ios - Xamarin Storyboard 在构建 661 后无法正确呈现

xamarin - 让图像只占据剩余空间

xamarin - 如何修复异常 System.TypeLoadException : VTable setup of type Xfx. Controls.Droid.Renderers.XfxCardViewRendererDroid 失败

xamarin - 如何在没有后退按钮的情况下在 Xamarin Shell 中切换页面?

xamarin - 当 Xamarin 聚焦时,如何确保键盘不会放置在条目上方?