[英]multithreading behavior strange C#!
这是我的应用程序,以执行线程示例为例,但是输出与预期不符,任何人对此都有任何线索
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__
究竟发生了什么事,任何人都可以解释,谢谢
这是由于访问“修改后的闭包”引起的 。
将循环的主体更改为此:
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
循环而言未修复。)
关闭。 您必须在线程中复制大量变量以使其保持当前值。
现在,所有线程都将读取它们运行时具有的任何值的变量i-而不是为其调用thread.start时具有的值。
在for循环内创建Thread
对象时,不会调用testThread
每当计划线程运行时,都会调用该方法。 那可能会在以后发生。
在您的情况下,线程在for循环结束后开始运行-那时i
等于3。因此testThread
被调用3次,值3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.