![](/img/trans.png)
[英]Reading text file into string array - why am I getting unexpected output?
[英]Why am I getting unexpected output when spawning threads?
我試圖產生一定數量的線程。 但是當我向函數傳遞參數時,輸出是隨機的。 它多次選擇變量'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();
}
}
由於關閉 :
將您的代碼更改為:
int i;
for (i = 0; i < 10; i++)
{
int j = i;
Thread th1 = new Thread(()=>tone(j) );
th1.Start();
// Console.WriteLine(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.