I'm trying to have 2 tasks run one after the other, but I don't want to wait for them to finish since I'll be doing that later.
Initially I had an implementation with ContinueWith but the double await was bothering me and I don't see Unwrap() as a significant improvement.
I decided to do a PoC to create the 2 tasks separately and have another task dispatched to manage them while I return the 2 initial tasks but weirdly the tasks become marked as completed as soon as I hit the await Task.Delay() which basically means that in reality they're running concurrently.
This is the code:
var task1 = new Task(async ()=>
{
Console.WriteLine("Task1 Start");
await Task.Delay(5000);
Console.WriteLine("Task1 STOP");
});
var task2 = new Task(async () =>
{
Console.WriteLine("Task2 Start");
await Task.Delay(5000);
Console.WriteLine("Task2 STOP");
});
var taskParent = Task.Run(async () =>
{
Console.WriteLine("starting 1");
task1.Start();
await task1;
Console.WriteLine("starting 2");
task2.Start();
await task2;
});
Console.WriteLine("BEGIN await parent");
await taskParent;
Console.WriteLine("END await parent");
and the output is
BEGIN await parent
starting 1
Task1 Start
starting 2
Task2 Start
END await parent
Task2 STOP
Task1 STOP
So I go from my desire to have task2 begin after task1 to it finishing before task1 does. I can't see a reason why calling await Task.Delay would mark the tasks as complete. Am I missing something?
EDIT To simplify my requirements since there seems to be a bit of confusion. The tasks must be returned before they are awaited, and the second task must run after the first. Some other thread will want the result later on and if it is completed fine if not it will await. I need to be able to await the second task and expect that the first one is executed before the second one.