SB2055 SB2055 - 1 month ago 13
C# Question

Why is await exiting?

Given the following code:

public async Task Send() // part of Sender class
{
// sync code
}

// //

private async Task HandleMessage()
{
// await sender.Send(); // exits HandleMessage immediately
sender.Send().Wait(); // works as expected, waiting to complete
DoOtherStuff(); // doesn't get hit with await
return;
}

RunRecurringTask(async () => await HandleMessage(), result);

public void RunRecurringTask(Action action, RecurringTaskRunResult result)
{
action();
result.DoStuff();
}


I thought that
await
tells the thread to come back when the awaited thing is complete, but it looks like for some reason that's not happening: the remaining code is never hit and everything just... stops. What could be causing this?

This is a console application in an Azure WebJob, for what it's worth. When
Wait
is used, I get the expected results, however with
await
, the job just completes.

Answer

You should never do async void unless you are writing a event handler. A Action with the async modifier is a async void method. You need to make the argument a Func<Task> and then do await action() in your RunRecurringTask

private async Task HandleMessage()
{
    await sender.Send();
    DoOtherStuff();
    return;
}

RunRecurringTask(async () => await HandleMessage(), result);
//You also could do 
//RunRecurringTask(() => HandleMessage(), result);

public async Task RunRecurringTask(Func<Task> action, RecurringTaskRunResult result)
{
        await action();
        result.DoStuff();
}

If you had other methods that where not marked with async you will need to change all of them up the call stack till you get to the entry point from the SDK. The SDK understands how to handle functions with a async Task return type since the 0.4.0-beta version.