Using async await still freezes GUI

后端 未结 2 1297
有刺的猬
有刺的猬 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:02

    You can use Task.Run or Task.Factory.StartNew to execute Test() or some long running and/or blocking operation on another thread:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await Task.Run(() => Test());
        txtResult.Text = "Done!";
    }
    
    0 讨论(0)
  • 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<int> 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
    }
    
    0 讨论(0)
提交回复
热议问题