正在更改的线程参数 [英] Thread parameters being changed
问题描述
启动多线程时,我解析的id
参数有时是错误的.这是我的启动:
When starting multiple threads, the id
parameter I'm parsing is sometimes wrong. Here is my startup:
for (int i = 0; i < _threadCount; i++)
{
Thread thread = new Thread(() => WorkerThread(i));
thread.Start();
_threads.Add(thread);
}
还有我的线程函数:
private void WorkerThread(int id)
{
Console.WriteLine("[{0}] Thread started {1}", DateTime.Now.ToLongTimeString(), id);
}
这段代码的输出是:
[19:10:54] Thread start 3
[19:10:54] Thread start 9
[19:10:54] Thread start 4
[19:10:54] Thread start 12
[19:10:54] Thread start 11
[19:10:54] Thread start 3
[19:10:54] Thread start 12
[19:10:54] Thread start 6
[19:10:54] Thread start 9
[19:10:54] Thread start 6
[19:10:54] Thread start 13
[19:10:54] Thread start 2
[19:10:54] Thread start 15
[19:10:54] Thread start 9
[19:10:54] Thread start 15
在我看来,这段代码应该使用唯一的 id
创建每个线程,而不是像上面看到的那样重复.
Where in my mind, this code should create every thread with a unique id
instead of duplicates as seen above.
编译器信息:
平台目标:x64
目标框架:.NET Framework 4.5
Target Framework: .NET Framework 4.5
推荐答案
你应该小心在启动线程后不小心修改了像 i
这样捕获的变量,因为 i
共享.i
变量在整个循环的生命周期中引用相同的内存位置.解决方案是使用一个临时变量,如下所示:
You should be careful about accidentally modifying captured variables like i
after starting the thread, because the i
is shared. The i
variable refers to the same memory location throughout the loop’s lifetime. The solution is to use a temporary variable like this:
for (int i = 0; i < _threadCount; i++)
{
var i1 = i;
Thread thread = new Thread(() => WorkerThread(i1));
thread.Start();
_threads.Add(thread);
}
在此处阅读有关闭包的更多信息:闭包之美来自(Jon Skeet) 和 Lambda 表达式和从 (约瑟夫·阿尔巴哈里).
Read more about Closures here : The Beauty of Closures from (Jon Skeet) and Lambda expressions and captured variables from (Joseph Albahari).
这篇关于正在更改的线程参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!