I expected that the thread in which the Main
method works will be busy executing Task.WaitAll
and n-1 threads will remain for the rest of the tasks, where n is the maximum CPU threads in the system. And in the case of using await Task.WhenAll
, the thread in which the Main
method works will not be busy executing await Task.WhenAll
, and n threads will remain for the rest of the tasks. But in reality there is no difference.
Question:
In this example, the advantage of using await Task.WhenAll
is precisely that the system does not need to spend resources to create a new "software thread"? Am I thinking right?
Example:
int Tasks = Environment.ProcessorCount * 2;
int Count = 0;
List<Task> MyListForTask = new List<Task>();
void MyMethod()
{
lock (MyListForTask)
{
Count++;
}
Console.WriteLine(Count);
int Sum = int.MaxValue;
while (Sum > 0)
{
Sum--;
}
}
//Option 1: Task.WaitAll. For a machine with 16 threads: 16 + 16 runs
for (int i = 0; i < Tasks; i++)
{
MyListForTask.Add(new Task(MyMethod));
MyListForTask[i].Start();
}
Console.WriteLine("Method Main works");
Task.WaitAll(MyListForTask.ToArray());
Console.WriteLine("\n");
MyListForTask.Clear();
Count = 0;
//Option 2: await Task.WhenAll. For a machine with 16 threads: 16 + 16 runs
for (int i = 0; i < Tasks; i++)
{
MyListForTask.Add(new Task(MyMethod));
MyListForTask[i].Start();
}
Console.WriteLine("Method Main works");
await Task.WhenAll(MyListForTask.ToArray());