async Task is freezing the UI

前端 未结 3 1926
無奈伤痛
無奈伤痛 2021-01-06 04:27

I have a method like this:

private async Task DoSomething()
{
    // long running work here.
}

When I call the method like this it blocks t

相关标签:
3条回答
  • 2021-01-06 04:50

    async methods begin their execution synchronously. async is useful for composing asynchronous operations, but it does not magically make code run on another thread unless you tell it to.

    You can use Task.Run to schedule CPU-bound work to a threadpool thread.

    See my async / await intro post or the async FAQ for more information.

    0 讨论(0)
  • 2021-01-06 04:59

    Without the actual code, it's hard to tell you what's going on, but you can start your DoSomething with 'await Task.Yield();' to force it to return immediately, in case what's running before the first await is what's causing your UI issue.

    0 讨论(0)
  • 2021-01-06 05:15

    How are you using await? This doesn't block the UI:

        private async Task DoSomething()
        {
            await Task.Delay(5000);
        }
    
        private async void button1_Click(object sender, EventArgs e)
        {
            await DoSomething();
            MessageBox.Show("Finished");
        }
    

    Note that I didn't have to write any verbose callback stuff. That's the point of async/await.

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