这种使用 Parallel.ForEach() 线程安全吗? [英] Is this use of Parallel.ForEach() thread safe?

查看:63
本文介绍了这种使用 Parallel.ForEach() 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在处理这个:

Essentially, I am working with this:

var data = input.AsParallel();
List<String> output = new List<String>();

Parallel.ForEach<String>(data, line => {
    String outputLine = ""; 
    // ** Do something with "line" and store result in "outputLine" **

    // Additionally, there are some this.Invoke statements for updating UI

    output.Add(outputLine);
});

输入是一个 List 对象.ForEach() 语句对每个值进行一些处理,更新 UI,并将结果添加到 output List.这有什么本质上的错误吗?

Input is a List<String> object. The ForEach() statement does some processing on each value, updates the UI, and adds the result to the output List. Is there anything inherently wrong with this?

注意事项:

  • 输出顺序不重要

更新:

根据我收到的反馈,我在 output.Add 语句以及 UI 更新代码中添加了手动 lock.>

Based on feedback I've gotten, I've added a manual lock to the output.Add statement, as well as to the UI updating code.

推荐答案

Yes;List 不是线程安全的,因此从任意线程(很可能同时)临时添加到它是注定要失败的.您应该改用线程安全列表,或者手动添加锁定.或者也许有一个 Parallel.ToList.

Yes; List<T> is not thread safe, so adding to it ad-hoc from arbitrary threads (quite possibly at the same time) is doomed. You should use a thread-safe list instead, or add locking manually. Or maybe there is a Parallel.ToList.

另外,如果有问题:将无法保证插入顺序.

Also, if it matters: insertion order will not be guaranteed.

这个版本是安全的:

var output = new string[data.Count];

Parallel.ForEach<String>(data, (line,state,index) =>
{
    String outputLine = index.ToString();
    // ** Do something with "line" and store result in "outputLine" **

    // Additionally, there are some this.Invoke statements for updating UI
    output[index] = outputLine;
});

这里我们使用 index 来更新每个并行调用的不同数组索引.

here we are using index to update a different array index per parallel call.

这篇关于这种使用 Parallel.ForEach() 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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