ispiro
ispiro

Reputation: 27633

Non-awaited async methods run on the UI thread?

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 iteration - the UI should be updated with the result of M2.

In order to await M2, M1 needs to be async. But M1 should run on the UI thread (to avoid race conditions) and therefore it will be called without an await.

Am I correct in thinking that in this way, M1's updating of the UI will be on the UI thread?


(Extra: It seems OK to have an async void in this case. Is this correct?)

Upvotes: 1

Views: 435

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

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
}

Upvotes: 1

Related Questions