我在循环中创建线程,我需要在线程启动方法中传递循环计数器(就像创建线程时一样).
for (int i = 0; i < ListSize; i++)
{
thread = new Thread(() =>
Helper.GetEndToEndRequestProcessTime(EmailList[i], reqResultData, i, ListSize));
workerThreads.Add(thread);
thread.Start();
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子i中,变量I作为参数GetEndToEndRequestProcessTime().但问题是,实际线程的起始值i正在发生变化,而我的结果却是错误的GetEndToEndRequestProcessTime().
如何确保在线程启动时传递的值GetEndToEndRequestProcessTime()与创建线程时提供的值相同.
每个新手必须要求的经典闭包和捕获变量问题.
for (int i = 0; i < ListSize; i++)
{
var j = i;
thread = new Thread(() => Helper.GetEndToEndRequestProcessTime(EmailList[j], reqResultData, j, ListSize));
workerThreads.Add(thread);
thread.Start();
}
Run Code Online (Sandbox Code Playgroud)
欲了解更多信息:http://csharpindepth.com/articles/chapter5/closures.aspx
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |