My async Task always blocks UI

前端 未结 2 1108
广开言路
广开言路 2021-01-04 06:21

In a WPF 4.5 application, I don\'t understand why the UI is blocked when I used await + a task :

    private async void Button_Click(object sender, RoutedEve         


        
相关标签:
2条回答
  • 2021-01-04 06:59

    Try this:

    private Task<double> JobAsync(double value)
    {
        return Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 30000000; i++)
                value += Math.Log(Math.Sqrt(Math.Pow(value, 0.75)));
    
            return value;
        });
    }
    
    0 讨论(0)
  • 2021-01-04 07:05

    You should be getting a warning about JobAsync - it contains no await expressions. All your work is still being done on the UI thread. There's really nothing asynchronous about the method.

    Marking a method as async doesn't make it run on a different thread - it's more that it makes it easier to join together asynchronous operations, and come back to the appropriate context.

    I suspect it would be a good idea to take a step back and absorb some of the materials about async on MSDN... this is a good starting point...

    0 讨论(0)
提交回复
热议问题