I have an exercise in asynchronous programming like this:
There are 4 Tasks: Task1
, Task2
, Task3
, Task4
.
Task1
and Task2
run in parallel. Task3
is only run when either Task1
or Task2
completes. Task4
runs when all 3 previous tasks must be completed.
This is how I do it, but my teacher asked me not to separate the function to handle Task.WaitAny()
(in the picture is the waitAny()
function), and not to use async in ContinueWith
.
Can someone help me?
Screenshot with code.
static async Task<int> waitAny()
{
return Task.WaitAny(runTask1(), runTask2());
}
static void Main(string[] args)
{
waitAny().ContinueWith(
async (_taskToContinue) =>
{
await runTask3();
Task.WaitAll(runTask1(), runTask2(), runTask3());
await runTask4();
});
Console.ReadKey();
}
CodePudding user response:
Would do it like this then.
static void Main(string[] args)
{
var task1 = runTask1();
var task2 = runTask2();
Task.WhenAny(task1, task2).ContinueWith(task =>
{
var task3 = runTask3();
Task.WaitAll(task1, task2, task3);
var task4 = runTask4();
task4.Wait();
});
}