Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting unexpected output when spawning threads?

I was trying to spawn certain number of threads. But when I pass arguments to the function the output is random. It chooses some values of variable 'i' for multiple times and ignores some. I am a newbie in C#. Please explain if I am doing anything wrong.

using System;
using System.Threading;

public class first
{
     public static void tone(int i)
{
        Console.WriteLine("Hi ! this is thread : {0} ",i);
        Thread.Sleep(10);
}

public static void Main(String[] args)
{
    int i;
    for (i = 0; i < 10; i++)
    {
        Thread th1 = new Thread(()=>tone(i) );
        th1.Start();
       // Console.WriteLine(i);
    }
    Console.WriteLine("hey there!");
    Console.ReadLine();
}

}

enter image description here

like image 770
Anand Avatar asked Mar 20 '23 14:03

Anand


1 Answers

Because of closure:

Change your code to:

int i;
    for (i = 0; i < 10; i++)
    {
       int j = i;
        Thread th1 = new Thread(()=>tone(j) );
        th1.Start();
       // Console.WriteLine(i);
    }
like image 83
Toan Nguyen Avatar answered Apr 01 '23 01:04

Toan Nguyen