有一个紧密的循环,通过调用QueueUserWorkItem
将工作排队到不同的线程。
我想知道每个循环执行是否可能会更改作为参数传递给前一个池线程的内容。
List<object> list = new List<object>();
for (int i = 0; i < list.Count; i++)
{
object param = list[i];
ThreadPool.QueueUserWorkItem(x => { MethodWithParameter(x); }, param);
}
最佳答案
I was wondering if each loop execution could potentially be changing what was passed as the argument to the previous pool thread
不,将任务排队到池中的代码部分是同步的
// here you are assigning the value that
// will be used as the state for the task when it is run
object param = list[i];
ThreadPool.QueueUserWorkItem(x => { MethodWithParameter(x); }, param);
因此,无论调用方法 QueueUserWorkItem
时 param
的值是什么,任务启动时都将作为 x
传递
做这样的事情可能会遇到麻烦:
object param = null;
for (int i = 0; i < list.Count; i++)
{
//even though you are assigning a value to param here
//there is no telling when the task will actually execute
param = list[i];
ThreadPool.QueueUserWorkItem(x => { MethodWithParameter(param); }, null);
}
因为当任务实际执行时,不知道param的值会是多少。
关于c# - 传递给在紧密循环中生成的线程的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860903/