I'm new to C# and especially to async methods. I've got a question about tasks in a for loop and why the called methods don't take the by me expected loop counter as the parameter.
Here is my program: I have an easy class "DoSomething" with only one method, called "TakeAndReturnInt". This methods has an int as a parameter und just returns it after 2 seconds delay.
public class DoSomething
{
public int TakeAndReturnInt(int count)
{
Thread.Sleep(2000);
return count;
}
}
In my asynchronous method I create a List of tasks, call the function 10 times asynchronously and add the return task to my tasklist. Before I write the returned values by using a foreach loop to the console, I await the finishing of all tasks in my tasklist and write the result to an array "result from which i write to console".
class Program
{
static void Main(string[] args)
{
var watch = new Stopwatch();
watch.Start();
RunAsync().Wait();
watch.Stop();
Console.WriteLine($"The elapsed time is: {watch.ElapsedMilliseconds} ms");
}
public static async Task RunAsync()
{
var myObj = new DoSomething();
List<Task<int>> tasklist = new List<Task<int>>();
for (int i = 0; i < 10; i++)
{
//await Task.Delay(300);
tasklist.Add(Task.Run(() => myObj.TakeAndReturnInt(i)));
}
var result = await Task.WhenAll(tasklist);
foreach (int myresult in result)
{
Console.WriteLine(myresult);
}
}
}
If I don't use the Task.Delay() method, the output is: 10 10 10 10 10 10 10 (10 times), if i use the await Task.Delay() method it is: 1 2 3 4 5 6 7 8 9 10. I recognized that the output sometimes is not 1 2 3 4.... but a shuffled order like 8 6 9 10 3 4 1.... (without using Task.Delay())
My questions are:
- Why does the value 10 appear and the 0 is missing? The loop is from 0 to 9.
- Why does the method returns always the 10 if i don't use await Task.Delay()?
- And why is the order shuffled from time to time? The starting of the tasks and the adding to the tasklist should be in the sequence 0 1 2 3 4... no? The finishing sequence of the tasks shouldn't change the order in the list and the result array in my understanding.
Thanks for your help.