Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

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?


Solution

  • 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;
    });