Riyas Khan
Riyas Khan

Reputation: 13

C# Multi threading using Task class

I've been trying to implement multi threading which looks something like this:

static void Main(string[] args)
{
        List<Task> tskList = new List<Task>();
        for (int i = 0; i < 100; i++)
        {
            Task taskTemp = new Task(() => { Display(i); });
            taskTemp.Start();
            tskList.Add(taskTemp);

            //Thread.Sleep(10);
        }

        Task.WaitAll(tskList.ToArray());
}

public static void Display(int value)
{
        Thread.Sleep(1000);
        Console.WriteLine(value);
}

Without the Thread.Sleep(10) part, I get output printed as 100 times "100" instead of 0 to 99 which I'm getting with that sleep time of 10 ms. My guess is that this could be happening because of the time required to schedule the thread by the system and by the time the thread is about to actually start, the value has reached 100. If I put enough wait time (say 1000 ms instead of 10), will it be guaranteed to not have this problem? Or should I suspect that the system may take even more time to schedule the thread when CPU utilization is too much? What is the best way to solve this problem?

Thanks in advance for any inputs!

Upvotes: 1

Views: 71

Answers (2)

Gavin Fang
Gavin Fang

Reputation: 367

you should add a local variable to hold 'i', such as :

 for (int i = 0; i < 100; i++)
    {
        var t = i;
        Task taskTemp = new Task(() => { Display(t); });
        taskTemp.Start();
        tskList.Add(taskTemp);

        //Thread.Sleep(10);
    }

Upvotes: 2

user6522773
user6522773

Reputation:

Just make a copy of "i" to "i1" and use it as local variable. "i" is always changed, thats why you get 100 100 100....:

private static void Main(string[] args)
{
  var tskList = new List<Task>();
  for (var i = 0; i < 100; i++)
  {
    var i1 = i;
    var taskTemp = new Task(() => { Display(i1); });
    taskTemp.Start();
    tskList.Add(taskTemp);
  }
  Task.WaitAll(tskList.ToArray());
}

public static void Display(int value)
{
  Thread.Sleep(1000);
  Console.WriteLine(value);
}

Upvotes: 1

Related Questions