这是我的应用程序,用于执行线程示例,但输出与预期不符,请有人对此有任何线索
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace OTS_Performence_Test_tool
{
class Program
{
static void testThread(string xx)
{
int count = 0;
while (count < 5)
{
Console.WriteLine(xx );
count++;
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello to the this test app ---");
for (int i = 1; i<=3; i++)
{
Thread thread = new Thread(() => testThread("" + i + "__"));
thread.Start();
}
Console.ReadKey();
}
}
}
但出来却是
3__
3__
3__
3__
3__
3__
3__
3__
3__
3__
4__
4__
4__
4__
4__
到底发生了什么任何人都可以解释 谢谢
最佳答案
See Eric Lippert's excellent blog post on this issue.
这是由访问 "modified closure" 引起的.
将循环的主体更改为:
for (int i = 1; i<=3; i++)
{
int j = i; // Prevent use of modified closure.
Thread thread = new Thread(() => testThread("" + j + "__"));
thread.Start();
}
(请注意,对于 foreach
循环,这已在 .Net 4.5 中得到修复,但对于 for
循环则未修复。)
关于c# - 多线程行为奇怪的 C#!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861437/