[英]Xamarin Forms Best way to run a background thread
I have a question.我有个问题。 I am building an app that collects stock market prices, but now the most important part is where I do a call every x seconds to get the new price.我正在构建一个收集股票市场价格的应用程序,但现在最重要的部分是我每 x 秒调用一次以获取新价格。 The variable of the price is located in the App.xaml.cs, so it is global for every page, but now I need to update it with the following line every 3 seconds: CoinList = await RestService.GetCoins();
price 的变量位于 App.xaml.cs 中,因此它对于每个页面都是全局的,但现在我需要每 3 秒使用以下行更新它: CoinList = await RestService.GetCoins();
The function must be async because the whole RestService is async! function 必须是异步的,因为整个 RestService 是异步的!
I already found something like this:我已经找到了这样的东西:
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;
});
But I don't know if this is the best way to do it and where I should put it, because it is the most essential part of my app!但我不知道这是否是最好的方法以及我应该把它放在哪里,因为它是我的应用程序中最重要的部分!
Any suggestions?有什么建议么?
This is one case where would recommend async void
over a non-awaited Task.Run
, because not awaiting the Task.Run
task would silently swallow exceptions:这是一种建议async void
而不是未等待的Task.Run
的情况,因为不等待Task.Run
任务会默默地吞下异常:
Device.StartTimer(TimeSpan.FromSeconds(3), async () =>
{
CoinList = await RestService.GetCoins();
return true;
});
Just wrap the async method into a Task.Run
, check the code below.只需将异步方法包装到Task.Run
中,检查下面的代码。
Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
Task.Run(async () =>
{
CoinList = await RestService.GetCoins();
});
return true;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.