Complete long tasks without freezing the user interface

I am trying to execute an action in the background without freezing the user interface.

Of course, I could use BackgroundWorker for this.

However, I would like to do this only using task APIs.

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 that uses only Tasks?

+6
source share
1 answer

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 performs an operation in the thread pool thread and returns a Task representing this operation.

If you use Task.Wait in the async method, you are doing it wrong . You should await tasks in async methods, never block them.

+12
source

Source: https://habr.com/ru/post/912695/


All Articles