如何在C#中的一个整数锁定? [英] How to lock on an integer in C#?

查看:122
本文介绍了如何在C#中的一个整数锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以在C#中的一个整数锁定?整数不能与锁使用,因为它们是盒装(和引用仅锁定锁)。

Is there any way to lock on an integer in C#? Integers can not be used with lock because they are boxed (and lock only locks on references).

的情况如下:我有一个论坛型网站有节制功能。我想要做的就是确保不超过一个主持人可以在任何给定的时间主持一职。要做到这一点,我要上的帖子的ID锁。

The scenario is as follows: I have a forum based website with a moderation feature. What I want to do is make sure that no more than one moderator can moderate a post at any given time. To achieve this, I want to lock on the ID of the post.

我有一对夫妇的想法而已(例如使用字典< INT,对象>),但我正在寻找一个更好的和更清洁的方式

I've had a couple of ideas so far (e.g. using a dictionary<int, object>), but I'm looking for a better and cleaner way.

有什么建议?

推荐答案

我喜欢做这样的

public class Synchronizer {
    private Dictionary<int, object> locks;
    private object myLock;

    public Synchronizer() {
        locks = new Dictionary<int, object>();
        myLock = new object();
    }

    public object this[int index] {
        get {
            lock (myLock) {
                object result;
                if (locks.TryGetValue(index, out result))
                    return result;

                result = new object();
                locks[index] = result;
                return result;
            }
        }
    }
}

然后,要在一个int,你只需(使用相同的同步每次)锁定

Then, to lock on an int you simply (using the same synchronizer every time)

lock (sync[15]) { ... }

本类返回相同的锁定对象时给出了相同的索引两次。当一个新的指数来,它在字典中的下一个时代创建一个对象,返回它,并将其存储。

This class returns the same lock object when given the same index twice. When a new index comes, it create an object, returning it, and stores it in the dictionary for next times.

它可以很容易地改变与任何结构或值类型一般的工作,或者是静态使同步器对象不必被传递

It can easily be changed to work generically with any struct or value type, or to be static so that the synchronizer object does not have to be passed around.

这篇关于如何在C#中的一个整数锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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