-2

How can I periodically update (i.e. all 10s) a class in my ViewModel by call an async Webservice call in a Win 8.1 Universal app? I tried with a DispatcherTimer but the timer can't handle the async part. Here is my code i tried:

_myTimer = new DispatcherTimer();
_myTimer.Interval = new TimeSpan(0, 0, 10);
_myTimer.Tick += timerTick;

protected async Task timerTick(object sender, object e)
{
    var handler = new HttpClientHandler();

    var client = new System.Net.Http.HttpClient(handler);

    string url = "url";

    using (Stream stream = await client.GetStreamAsync(new Uri(url)))
    {

    }
}
user2025830
  • 872
  • 2
  • 17
  • 37
  • You don't access your ViewModel from the background task. You subscribe to the background workers' "completed" event in your view model and do the update in the handler. – ChrisF Dec 17 '15 at 13:54
  • can you show me an example, how to handle this? – user2025830 Dec 17 '15 at 13:56
  • Take a look at https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx – ChrisF Dec 17 '15 at 14:07
  • BackgroundWorker is not available in Win 8.1 Universal app. Are there any other solutions? – user2025830 Dec 17 '15 at 14:11
  • Ah. You can implement the functionality yourself, but it's a long time since I had to do that. – ChrisF Dec 17 '15 at 14:36

1 Answers1

1

Your code looks correct. DispatcherTimer is a particular timer that can manipulate UI Thread (instead of Timer class which runs on another thread).

What do you want to mean with:

the timer can't handle the async part

Thanks!

Thomas LEBRUN
  • 436
  • 2
  • 7
  • my problem is the outputtype from the timerTick event. Because my return is a Task, but I can't handle it like this: _myTimer.Tick += await timerTick; – user2025830 Dec 18 '15 at 08:11
  • You don't have to await the output of the Tick event. Just await the needed method calls in the event handler. – Thomas LEBRUN Dec 18 '15 at 10:00