Using async await still freezes GUI

后端 未结 2 1293
有刺的猬
有刺的猬 2021-02-20 02:23

I would like to handle long running operation in separate thread and return control back to GUI thread ASAP using async/await pattern as follows:

private         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-02-20 03:19

    You're using Thread.Sleep which blocks the thread. Use Task.Delay instead, which uses a timer internally and asynchronously yields control back to the caller:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await TestAsync();
        txtResult.Text = "Done!";
    }
    
    private async Task TestAsync()
    {
        await Task.Delay(3000);
        return 0;
    }
    

    Edit

    As you posted new code, I suggest you isolate the callback that needs to run after the log running process, and save yourself the Dispatcher.Invoke and replace it with the use of async-await which will land you on the right synchronization context for you:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await Task.Run(Test);
        CallBack();
    }
    
    private void Callback()
    {
        txtResult.Text = "Done!"
    }
    
    private void Test()
    {
        Thread.Sleep(3000); //long running operation, not necessarily pause
    }
    

提交回复
热议问题