Non-awaited async methods run on the UI thread?

前端 未结 1 1468
终归单人心
终归单人心 2021-01-24 07:31

I want to have a method (Let\'s call it M1) execute some async code in a loop (Let\'s call that second method M2). On every iterat

相关标签:
1条回答
  • 2021-01-24 08:26

    Yes. (assuming you use Synchronization Context that returns to UI thread - i.e. one from WinForm/WPF).

    Note that it also means you can't schedule CPU-intensive operations that way as it will run on UI thread.

    Using void async is quite standard method of handling events in WinForms:

    void async click_RunManyAsync(...)
    {
       await M1();
    }
    
    void async M1()
    {
         foreach (...)
         {
            var result = await M2(); 
            uiElement.Text = result; 
         }
    }
    
    async Task<string> M2()
    {
        // sync portion runs on UI thread
        // don't perform a lot of CPU-intensive work
    
        // off main thread, same synchronization context - so sync part will be on UI thread. 
        var result = await SomeReallyAsyncMethod(...); 
    
        // sync portion runs on UI thread
        // don't perform a lot of CPU-intensive work
    }
    
    0 讨论(0)
提交回复
热议问题