当启动多个线程时,id
我正在解析的参数有时是错误的.这是我的创业公司:
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
而不是重复的每个线程,如上所示.
编译器信息:
平台目标:x64
目标框架:.NET Framework 4.5
你应该注意i
在启动线程之后意外修改捕获的变量,因为它i
是共享的.该i
变量指向同一个内存位置在整个循环的寿命.该溶液是使用临时变量是这样的:
for (int i = 0; i < _threadCount; i++) { var i1 = i; Thread thread = new Thread(() => WorkerThread(i1)); thread.Start(); _threads.Add(thread); }
阅读更多关于闭包的信息:闭塞之美(Jon Skeet)和Lambda表达式以及(Joseph Albahari)的变量.