线程安全数据集 [英] Thread-safe DataSet

查看:170
本文介绍了线程安全数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对DataTable / DataSet进行线程安全的更新操作。每个使用DataTable的 Rows.Find(pk)方法更新〜40行全局DataTable。每个线程将更新DataTable的不同行。

I want to make update operations to the DataTable/DataSet thread-safe. There are ~20 threads each updating ~40 rows of global DataTable using Rows.Find(pk) method of DataTable. Each thread will be updating distinct rows of DataTable.

我正在为DataSet使用以下包装类。这个方法线程安全吗?

I'm using the following wrapper class for DataSet. Is this approach thread-safe?

public sealed class MyDataSet{

    public static DataSet ds = new DataSet();

    public static UpdateRow(key,data)
    {
        object _lock = new object();
        DataRow dr = ds.Tables[0].Rows.Find(key);
        lock(_lock){          
            dr.AcceptChanges();
            dr.BeginEdit();
            dr["col"] = data;
            dr.EndEdit();
        }
    }
}

循环

for(int x=0; x<40; x++;){
    if(someCondition)
    .
    .
    .
    MyDataSet.UpdateRow(key,data);
    .
    .
    .
    }

一切都在多线程环境中完成。 UpdateRow方法线程安全吗?

Everything is done in a multithreaded environment. Is UpdateRow method thread safe?

推荐答案

不,这不安全。您应该更改代码:

No, it is not safe. You should change your code in:

public sealed class MyDataSet{

    public static DataSet ds = new DataSet();

    private static object _lock = new object();

    public static UpdateRow(key,data)
    {
        lock(_lock){
            DataRow dr = ds.Tables[0].Rows.Find(key);
            dr.AcceptChanges();
            dr.BeginEdit();
            dr["col"] = data;
            dr.EndEdit();
        }
    }
}

您的 _lock 对象应该是程序中的静态对象,使其成为一个很好的锁。而您的查找应该在锁定的部分。

Your _lock object should be a static object in your program to make it a good lock. And your Find should be in the locked part.

这篇关于线程安全数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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