在C#中使用并行Linq值Misssig [英] Values Misssig using Parallel Linq In C#

查看:95
本文介绍了在C#中使用并行Linq值Misssig的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我尝试使用Parallel Linq向对象添加数据.但是多次单击该按钮时,某些值会丢失.代码是

Hi All,

I''m tried Parallel Linq for adding data to an object. but some of the values are missing when clicking the button multiple times. The code is

BindingList<object> addnew = new BindingList<object>();
System.Threading.Tasks.Parallel.For(0, 1000, i =>
                addnew.Add(
                new object()
                )
                );
MessageBox.Show(addnew.Count.ToString());





please give a solution if any one know about this.

推荐答案

如果您在MSDN页面上查看 ^ ],您将在底部看到以下内容:
这种类型的任何公共静态(在Visual Basic中为Shared)成员都是线程安全的.不保证任何实例成员都是线程安全的."

这意味着线程相互干扰!您需要使用某种形式的lock:
If you look at the MSDN page for BindingList[^] you will see the following at teh bottom:
"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

This means that the threads are interfering with each other! You need to use a lock of some form:
BindingList<object> addnew = new BindingList<object>();
    System.Threading.Tasks.Parallel.For(0, 1000, i => AddOne(addnew));
    MessageBox.Show(addnew.Count.ToString());
    }
private void AddOne(BindingList<object> list)
    {
    lock (list)
        {
        list.Add(new object());
        }
    }


这篇关于在C#中使用并行Linq值Misssig的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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