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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With