In this example,
private async void Button1_Click(object sender, EventArgs e)
{
if (condition) await Task.Run(Foo);
}
private void Foo()
{
Thread.Sleep(5000);
}
sometimes condition is false, and the async method awaits nothing. But consider this example,
private async void Button1_Click(object sender, EventArgs e)
{
await Task.Run(Foo);
}
private void Foo()
{
if (condition) Thread.Sleep(5000);
}
where the method is always awaited, even if condition is false. I'm wondering what happens behind the scenes, if one is more preferable to the other, I mean objectively if there are compiler optimizations which make one preferable over the other. Assume condition can be checked from any thread, and has a very minimal impact to performance.
It seems that when the condition check is deferred, there is always a task being awaited, but when it's false in the handler, I have a situation which is close to one where the async method lacks an await operator, about which the compiler warns me. So it feels both wrong and right at the same time. Hoping someone can shed some objective light on this question.