螺纹参数被修改 [英] 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);
}
这段代码的输出是:
The output of this code is:
[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.
编译器信息:
目标平台:64
目标框架:.NET框架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);
}
了解更多的瓶盖的位置:瓶盖从美(乔恩斯基特的)和的 Lambda表达式并抓获从(约瑟夫阿尔巴哈利的)。
Read more about Closures here : The Beauty of Closures from (Jon Skeet) and Lambda expressions and captured variables from (Joseph Albahari).
这篇关于螺纹参数被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!