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
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
}