I have created this code to understand about "Task.WaitAll ()" in c#.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
namespace taskApp
{
class Program
{
static void Main(string[] args)
{
List<Task> p = new List<Task>();
Task task1 = MultipleTasks();
Task task2 = Hello(40);
Task task3 = Bye(10);
Task.WaitAll(task1, task2, task3);
var a = 1;
a = a + 1;
}
private static async Task Hello(int delay)
{
await Task.Delay(delay);
Console.WriteLine($"+++ End Process: {nameof(Hello)}, delay: {delay} +++ ");
}
private static async Task Bye(int delay)
{
await Task.Delay(delay);
Console.WriteLine($"+++ End Process: {nameof(Bye)}, delay: {delay} +++ ");
}
private static async Task<List<MyClass>> MultipleTasks()
{
List<Task<MyClass>> psTask = new List<Task<MyClass>>();
List<MyClass> ps = new List<MyClass>();
for (int i = 0; i < 3; i++)
psTask.Add(getTest(i));
Task.WaitAll(psTask.ToArray());
ps = psTask.Select(c => c.Result).ToList();
return ps;
}
private static async Task<MyClass> getTest(int i)
{
MyClass p = new MyClass();
int delay = 0;
switch (i)
{
case 0:
delay = 4000;
p.delayUsed = delay;
p.message = "cero";
break;
case 1:
delay = 1000;
p.delayUsed = delay;
p.message = "uno";
break;
case 2:
delay = 7000;
p.delayUsed = delay;
p.message = "dos";
break;
case 3:
delay = 2000;
p.delayUsed = delay;
p.message = "tres";
break;
default:
p.message = "default";
break;
}
await Task.Delay(p.delayUsed);
Console.WriteLine($"+++ End Process: {nameof(getTest)} {i}, delay: {delay} +++ ");
return p;
}
}
public class MyClass
{
public int delayUsed { get; set; }
public string message { get; set; }
}
}
This is the order that the console application runs
+++ End Process: getTest 1, delay: 1000 +++
+++ End Process: getTest 0, delay: 4000 +++
+++ End Process: getTest 2, delay: 7000 +++
+++ End Process: Bye, delay: 10 +++
+++ End Process: Hello, delay: 40 +++
The correct order that my application should run is as follows:
+++ End Process: Bye, delay: 10 +++
+++ End Process: Hello, delay: 40 +++
+++ End Process: getTest 1, delay: 1000 +++
+++ End Process: getTest 0, delay: 4000 +++
+++ End Process: getTest 2, delay: 7000 +++
Following the logic of the delay time of each method, the correct execution order is deduced
This is the help that "visual studio 2019" gives me.
And effectively the "MultipleTasks ()" method is executed synchronously.
Can someone tell me how I can make the console application behave correctly?.