Ana*_*and 4 .net c# multithreading
我试图产生一定数量的线程.但是当我向函数传递参数时,输出是随机的.它多次选择变量'i'的某些值并忽略一些.我是C#的新手.请解释我做错了什么.
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();
}
Run Code Online (Sandbox Code Playgroud)
}
由于关闭:
将您的代码更改为:
int i;
for (i = 0; i < 10; i++)
{
int j = i;
Thread th1 = new Thread(()=>tone(j) );
th1.Start();
// Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)