Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running long tasks without freezing the UI

I am trying to perform an action in the background, without freezing the UI.

Of course, I could use BackgroundWorker for this.

However, I'd like to do it with the Task API only.

I tried:

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   await LongOperation();
}
// It freezes the UI

and

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   var task = Task.Run(()=> LongOperation());
   task.Wait();
}


// It freezes the UI

So should I go back to BackgroundWorker? Or is there a solution using Tasks only?

like image 495
user380719 Avatar asked Apr 08 '12 17:04

user380719


1 Answers

You were pretty close.

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
  await Task.Run(() => LongOperation());
}

async does not execute a method on a thread pool thread.

Task.Run executes an operation on a thread pool thread and returns a Task representing that operation.

If you use Task.Wait in an async method, you're doing it wrong. You should await tasks in async methods, never block on them.

like image 138
Stephen Cleary Avatar answered Oct 13 '22 23:10

Stephen Cleary