Xamarin Forms 运行后台线程的最佳方式

问题描述 投票:0回答:1

我有一个问题。我正在建立一个收集股市价格的应用程序,但现在最重要的部分是我每隔x秒调用一次以获得新的价格。价格的变量位于App.xaml.cs中,所以它对每个页面都是全局的,但是现在我需要每3秒更新一次下面这行。CoinList = await RestService.GetCoins();

这个函数必须是异步的 因为整个RestService都是异步的!

我已经找到了这样的东西。

var minutes = TimeSpan.FromMinutes (3); 

Device.StartTimer (minutes, () => {

    // call your method to check for notifications here

    // Returning true means you want to repeat this timer
    return true;
});

但我不知道这是否是最好的方法,我应该把它放在哪里,因为它是我的应用程序中最重要的部分!

有什么建议吗?

c# xamarin xamarin.forms xamarin.android xamarin.ios
1个回答
0
投票

只要把async方法包进一个 Task.Run, 检查下面的代码 .

Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
  Task.Run(async () =>
  {
    CoinList = await RestService.GetCoins();
  });
  return true;
});

0
投票

这是一个情况下,将建议 async void 翘首以待 Task.Run,因为没有等待 Task.Run 任务会默默地吞下异常。

Device.StartTimer(TimeSpan.FromSeconds(3), async () =>
{
  CoinList = await RestService.GetCoins();
  return true;
});
© www.soinside.com 2019 - 2024. All rights reserved.