Running long tasks without freezing the UI
microsoft-metro, task, wpf
Solution
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.
Problem
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?