简体   繁体   中英

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. 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();

The function must be async because the whole RestService is async!

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM