C#并发,锁定和字典对象

编程入门 行业动态 更新时间:2024-10-27 04:24:42
本文介绍了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:

  • 使用字典< int,object> 作为padLocks类型,并将一个 ); 作为值。
  • 创建一个简单地保存id的类;
  • Use a Dictionary<int,object> as padLocks' type, and put a new object(); as the value.
  • 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#并发,锁定和字典对象

    本文发布于:2023-11-10 01:50:38,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1574026.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字典   对象

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!