-1

I have this lines of source

for (int i = 0; i < 100; i++)
{
   Task.Run(()=> Console.WriteLine(i));
}

I was expecting an output like 0,1,2,3,...,99 , but all I get is 100,100,100,...,100

I am not asking for a solution to get the output I want, all I'm asking is what call is being queued to the Threadpool.

I imagine something like Console.Writeline(reference on i) is being queued to the Threadpool.

Can someone explained how my code is treated and why?

SpyrosLina
  • 131
  • 7
  • did you at least tried to google for "C# starting tasks in loop" ? first result points to similar question already asked here – Selvin Apr 23 '19 at 08:30
  • As I said , I'm not looking for a solution. I am looking for what is being queued to the ThreadPool. (Yes 'sent' is not the correct word) – SpyrosLina Apr 23 '19 at 08:38

1 Answers1

0

You need to make a local copy of the variable before using it because i will change by the time the thread sees it:

for (int i = 0; i < 100; i++)
{
   var x = i;
   Task.Run(()=> Console.WriteLine(x));
}