使用锁的最佳做法 [英] Best Practices in using a lock

查看:45
本文介绍了使用锁的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在某些类中具有以下属性,并且其目的是用作锁.

Suppose I have the following property in some class, and its purpose is to be used as a lock.

protected object SyncRoot { get; private set; }

无论如何,无论设置方式和设置方式如何.事实上,如果已设置,使用该方法的最佳实践是什么?

Anyways, regardless of how and if this was set. What is best practice to go about using it if it is, in fact, set?

由于锁不适用于null对象,我应该这样处理吗?

Since lock does not work with null objects, should I handle it like this?

lock (SyncRoot ?? new object())
    SomeMethod();

还是应该这样检查null?

Or should I check for null like this?

if (SyncRoot != null)
    lock (SyncRoot)
        SomeMethod();
else
    SomeMethod();

实际上,如果已设置,我想用它来锁定.否则,我不在乎.无论如何,第一个解决方案是效率低下还是多余?

If it is, in fact, set, I'd want to use it to lock. Otherwise, I don't care. Is the first solution inefficient or redundant in anyway?

所有这些答案都很好.但是,我只能选一个.考虑到我与Luke讨论过的情况,没有理由为什么我的SyncRoot应该为null.在单线程环境中,锁的开销并不昂贵,但在多线程环境中则是必要的.

All these answers are good. However, I can only pick one. Given my situation as discussed with Luke, there is no reason why my SyncRoot should be null. The overhead of a lock in a single threaded environment is no biggy, but necessary if in a multi-threaded one.

(为Ya的所有4个投票投票)谢谢大家的迅速答复.

(Vote ups for all 4 of ya) Thank you all for your speedy replies.

推荐答案

我通常使用私有成员变量而不是属性,即

I normally use a private member variable not a property, ie

private static object MyLock = new object();

这样,它总是被初始化.

This way its always initialised.

您还可以使用非静态版本,例如

You can also use a non static version such as

private readonly object MyLock = new object();

这篇关于使用锁的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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