0

I try to run this code but the result I got that not as expected

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var tasks = new List<Task>();

            for (int i = 0; i < 100; i++)
            {
                var task = Task.Run(() =>
                {
                    Console.WriteLine(i);
                });
                tasks.Add(task);
            }
            Task.WaitAll(tasks.ToArray());

            Console.WriteLine("done");   
        }
    }
}

I expect the result is a list of 100 numbers 0 - 99 and not have duplicates

But I got a list that missing and duplicate like 6677899999...99 (miss 0 - 5 and duplicates) on https://dotnetfiddle.net/

I get a list of "100" if running on visual studio

So why this happen? Why is there a difference between visual studio and https://dotnetfiddle.net/? How to fix this?

Dan Nguyen
  • 1,308
  • 6
  • 17
  • @nikosi duplicate doesn’t explain why behavior seems different with different compiler versions though... – InBetween Dec 09 '18 at 20:20
  • I believe you not only use different compilers but they also differ in execution. Anyway, the reason for your result is clearly that `i` is not captured, meaning when the lambda method (`() => { Console.WriteLine(i);});`) evaluates it will use the current value of `i` which will likely have increased since the method was defined. And depending on the executing engine this value will likely vary. – Ykok Dec 17 '18 at 11:45

0 Answers0