c# - 传递给在紧密循环中生成的线程的参数

标签 c# concurrency

有一个紧密的循环,通过调用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);

因此,无论调用方法 QueueUserWorkItemparam 的值是什么,任务启动时都将作为 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/

相关文章:

c# - 如何通过套接字发送对象 C#

C#:如何在 API Controller 级别应用序列化来获取某些列

c# - 具有自引用类型约束的通用类

c# - BaseController参数化构造函数

java - volatile 示例(在 JLS8/8.3.1.4 volatile 字段中)不起作用?

java - 不同 JVM 之间共享的映射

multithreading - 乱序执行和重新排序 : can I see what after barrier before the barrier?

debugging - Go - 编译一组函数时出错

c# - 在 ASP.NET MVC 中使用或继承 DisplayAttribute 创建自定义显示属性

php - PHP 对 SQL 请求进行排队