C#并发,锁定和字典对象 [英] C# concurrency, locking and dictionary objects

查看:723
本文介绍了C#并发,锁定和字典对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆DB实体加载到DB对象。同一个DB实体可以加载到多个DB对象中。定期地,DB实体将需要特殊处理。该处理必须一次由一个线程执行。锁定是在这里。

I have a bunch of DB entities that are loaded into DB objects. The same DB entity may be loaded into more than DB object. Periodically a DB entity will require special processing. This processing must be performed by one thread at a time. Locking is in order here.

编辑:重要说明:该过程调用慢速Web服务。这是我试图阻止并发。我没有看到这是如何安全地执行锁定。

Important note: the process calls a slow web service. This is what I'm trying to prevent concurrency. I don't see how this can be done safely w/o locks.

所以我创建一个挂锁对象将由DB对象引用锁定。挂锁对象是基于实体的,因此同一实体的两个或多个DB对象将使用相同的挂锁对象。我使用DB实体的ID作为键,将这些挂锁存储在字典对象中。挂锁对象也是一个简单的字符串对象。这是正确的方法吗?我想我不是工程或简化这个。如果方法是正确的,这段代码怎么样?

So I create an "padlock" object that will be referenced by the DB objects for locking. The padlock object is entity based so that two or more DB objects for the same entity will use the same padlock object. I’m storing these padlocks in a dictionary object using the DB entity’s ID as the key. The padlock object is just a simple string object as well. Is this the right approach? I'm thinking I'm either over engineering or simplifying this. If the approach is correct, how does this code look? It works, but I've yet to test it under load.

感谢:)

public static func(CustomObject o)
{
    if (ReadyForUpdate(o))
    {
        lock (LookupPadLockByID(object.ID)
        {
            if (ReadyForUpdate(o))
            {
                PerformUpdate(object);
            }
        }
    }
}

private static readonly object padlockLock = new object();
private static readonly Dictionary<int, string> padLocks = new Dictionary<int,string>();
private static object LookupPadLockByID(int uniqueID)
{
    lock (padlockLock)
    {
        if (!padLocks.ContainsKey(uniqueID))
        {
            padLocks.Add(uniqueID, uniqueID + " is locked");
        }
    }

    return padLocks[uniqueID];
}


推荐答案

锁定字符串不是一个好主意,我建议两个选择:

Locking on a string is not a good idea. I suggest two alternatives:


  1. 使用字典< int,object> 作为padLocks类型,并将一个 ); 作为值。

  2. 创建一个简单地保存id的类;

  1. Use a Dictionary<int,object> as padLocks' type, and put a new object(); as the value.
  2. Create a class that simply holds the id; this would be better for readability if you ever want to look at your LockPad class while debugging.

LockPad类:

class LockPad {
    public int Id { get; private set; }

    public LockPad(int id) {
        this.Id = id;
    }

    public override string ToString() {
        return "lock of " + id.ToString();
    }
}

然后锁定该类。

这篇关于C#并发,锁定和字典对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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