C# Multiple Tasks inside Task

by Kevin Basov   Last Updated January 11, 2019 11:26 AM

I'm trying to run Tasks inside one task, idea is to run multiple Tasks which include more tasks.

Example with 2 Tasks which i run and wait to them to complete.

private async void Start_btn_ClickAsync(object sender, EventArgs e)
{ 
   var Task1 = Task.Run(async () => { await TestCycle(FirstNest); });
   var Task2 = Task.Run(async () => { await TestCycle(SecondNest); });
   await Task.WhenAll(Task1, Task2);
   // Do More stuff when TestCycles have been completed.
}

Inside Test Cycle I need to call different Tasks and Task 1 and Task 2 shouldn't influence eachother. I will start this Task to read some messages, both of these Tasks receive messages from different sources, but the function is same.

public Task TestCycle(Nest nest)
{
    // Do stuff
    // Start task which will be just looping trough messages.
   var TaskInsideTask = Task.Run(async () => await (ReadBroadcastMessagesInLoop(nest, CanBus)));
    // Do stuff
    // At this point I want to wait this Task to complete before moving forward.
   TaskInsideTask.Wait();
   // When TaskInsideTask has returned Completed, I do not want to return that task itself, but just to know that it has stopped/finished etc.
   // I return completed task to let know that everything is done in TestCycle, so Task1 or Task2 is ready.
   return Task.CompletedTask
}

My problem is that Task1 completes, but Task2 never does. (Atleast i think so, i don't know how should I check if Task has completed?) I think this because program never gets to point where TestCycles both have returned complete.

Little flowchart



Answers 1


Over complicating the matter.

public async Task TestCycle(Nest nest) {
    // Do stuff
    // Start task which will be just looping trough messages.
    await ReadBroadcastMessagesInLoop(nest, CanBus);
    // Do stuff        

    //If there is nothing else to be done after the await then remove it
    //and just return the Task from ReadBroadcastMessagesInLoop
}

In the event handler again no need to wrap

private async void Start_btn_ClickAsync(object sender, EventArgs e)  
   var Task1 = TestCycle(FirstNest);
   var Task2 = TestCycle(SecondNest);
   await Task.WhenAll(Task1, Task2);
   // Do More stuff when TestCycles have been completed.
}
Nkosi
Nkosi
January 11, 2019 11:25 AM

Related Questions


Updated May 29, 2017 22:26 PM

Updated July 16, 2017 22:26 PM

Updated October 25, 2018 09:26 AM

Updated December 05, 2017 11:26 AM