My async Task always blocks UI

若如初见. 提交于 2019-11-30 01:49:06

问题


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, RoutedEventArgs e)
    {
        // Task.Delay works great
        //await Task.Delay(5000);

        double value = await JobAsync(25.0);

        MessageBox.Show("finished : " + value.ToString());
    }

    private async Task<double> JobAsync(double value)
    {
        for (int i = 0; i < 30000000; i++)
            value += Math.Log(Math.Sqrt(Math.Pow(value, 0.75)));

        return value;
    }

The await Task.Delay works great, but the await JobAsync blocks the UI. Why ? Thank you.


回答1:


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;
    });
}



回答2:


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...



来源:https://stackoverflow.com/questions/12786758/my-async-task-always-blocks-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!