Call back to main thread from a Task

Jatin picture Jatin · May 25, 2013 · Viewed 18.3k times · Source

As i don' know about threads much i have a question. I wanna do something in background and in background method i wanna switch back to the main thread on certain condition otherwise work in background. How can i achieve this functionality? I am using a call to StartSyncThread from UI class(c#)

async void StartSyncThread()
{
    await DoSyncAsync();
}

Task DoSyncAsync()
{
    return Task.Run(() => DoSync());            
}

in DoSync method i wanna switch back to main thread so that i can change UI. Please give me a simple solution to do this. Thanks in advance!

Answer

Deeko picture Deeko · May 29, 2013

First start your async process, then call Dispatcher.BeginInvoke to get back on the UI thread.

Task.StartNew(() =>
{
   // Do Something Async

   Dispatcher.BeginInvoke(() =>
   {
      // Update Your UI Here 
   });
});

Note that Dispatcher is not a static - this relies on your code being a part of a member function for a UI object, like a method on your page object.