我可以在 Parallel Foreach 循环中使用局部变量吗(不会无意中重写以前的值) [英] Can I use local variables inside a Parallel Foreach loop (without unintentionally rewriting the previous value)

查看:25
本文介绍了我可以在 Parallel Foreach 循环中使用局部变量吗(不会无意中重写以前的值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图一次处理一个数据表中的记录.我是多线程环境的新手,我被要求使用 Parallel.Foreach 循环.我想知道在并行执行模式下如何处理局部变量.以下是我的代码.

So I am attempting to process records from a datatable one row at a time. I am new to multi-threaded environments and I was asked to use Parallel.Foreach Loop. I wanted to know how local variables are treated in a Parallel execution mode. Following is my code.

Parallel.ForEach(dtReportData.Tables[0].AsEnumerable(), drow =>
{
string strType = drow["type"];
//Based on this type, I am executing logic from a switch case.

});

现在.我想知道我是否可以声明并为循环内的变量赋值.例如,假设有 2 个线程并行运行.

Now. I want to know if I can declare and assign value to the variable inside the loop. For an instance, let's assume that there are 2 threads running in parallel.

线程 1 获取了一条记录,假设获取的值是Type1"并存储到 strType 中.现在,我希望我的代码执行类型Type1"的逻辑(假设我们已经为它编写了一个 switch case)

Thread 1 fetched a record and let's say that the value that was fetched was "Type1" and stored into strType. Now, I want my code to perform the logic for type "Type1" (Let's assume that we have written a switch case for it)

但是,让我们假设在线程 1 开始执行逻辑之前,线程 2 开始发挥作用.线程 2 将值Type2"分配给 strType.

However, let's assume that before Thread 1 starts executing the logic, thread 2 comes into play. Thread 2 assigns the value "Type2" to the strType.

现在,当线程 1 进入我的 Switch 块时,它将保持什么值?它是Type1"还是Type2".

Now, when Thread 1 goes to my Switch block, what value will it hold? Will it be "Type1" or "Type2".

请注意,我没有在 Foreach 循环外全局声明 String 变量的值,它在循环内,我相信每次都会创建一个新实例.

Note that I am not globally declaring the value of the String variable outside the Foreach loop, it's inside the loop and I believe that a new instance is created everytime.

推荐答案

变量 strType 是此 lambda 调用的本地变量,其他线程无法看到或修改它.它的值存储在当前线程的堆栈中.每个线程都有自己的堆栈,大小为 1MB.

The variable strType is local to this lambda invocation, and no other thread is able to see it or modify it. Its value is stored in the stack of the current thread. Each thread has its own stack, with a size of 1 MB.

作为旁注,请注意一般的 ADO.NET 类,尤其是 DataTable 类,不是线程安全的.如果你尝试从多个线程并行地改变它们,它们的内部状态可能会被破坏,它们的行为将变得不确定.

As a side note, be aware that the ADO.NET classes in general, and the DataTable class in particular, are not thread-safe. If you try to mutate them from multiple threads in parallel, their internal state may become corrupted, and their behavior will become undefined.

这篇关于我可以在 Parallel Foreach 循环中使用局部变量吗(不会无意中重写以前的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆