Reputation: 1467
Consider the following code
class Program
{
static void Continue()
{
Console.Out.WriteLine("Continue t1");
}
static async Task AsyncStart()
{
Console.Out.WriteLine("AsyncStart");
return;
}
static void Main(string[] args)
{
Task t3 = AsyncStart().ContinueWith((ant) => { Continue(); });
Console.Out.WriteLine("BEFORE");
Task.WhenAny(new Task[] { t3 });
Console.Out.WriteLine("AFTER");
}
}
The output is
AsyncStart
BEFORE
AFTER
Press any key to continue . . .
Continuation is not running!!!!
Yes, I understand the AsyncStart does not contain any await (CS1998), but I still expect t3 to run the continuation. I am missing something very basic
Upvotes: 3
Views: 187
Reputation: 13495
Task.WhenAny
returns a Task
which you either need to await
in which case you'll need to do in in an async
method (Main can't be marked as async
). Alternatively because you are in a console app you can call Task.WaitAll
and that should wait for the continuation to complete. In a GUI app WaitAll can cause a deadlock, but in a console app it is ok.
static void Main(string[] args)
{
Task t3 = AsyncStart().ContinueWith((ant) => { Continue(); });
Console.Out.WriteLine("BEFORE");
Task.WaitAll(new Task[] { t3 });
Console.Out.WriteLine("AFTER");
}
Upvotes: 1
Reputation: 17444
Your process ended before the continuation (which runs on a background thread) had the chance to run.
Upvotes: 8