为什么锁对象必须是只读的? [英] Why does the lock object have to be readonly?

查看:105
本文介绍了为什么锁对象必须是只读的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现锁时,我曾经在类内部创建一个私有对象:

When implementing a lock, I used to create a private object inside of my class:

如果我想确保它已锁定在创建我的课程的线程中:

If I want to be sure that it is locked in the thread that created my class:

private object Locker = new object();

如果我想确保它会为我的应用程序内的所有线程锁定:

If I want to be sure that it will be locked for all threads inside my application:

private static object Locker = new object();

但是在这里: 为什么锁对象必须是静态的?

以及其他一些问题,每个人都说对象必须是readonly.我还没有找到原因-甚至在MSDN或JavaDoc中也没有.

and in a number of other questions, everyone says that the object has to be readonly. I haven't found the reason - not even in MSDN or JavaDoc.

由于我经常使用这种构造,有人可以向我解释为什么我应该使用readonly吗?

As I use this kind of construction quite often, could someone explain to me why should I use readonly?

谢谢!

推荐答案

如果我想确保它对我内部的所有线程都被锁定 应用程序:

If I want to be sure that it will be locked for all threads inside my application:

如果锁对象将访问锁定为静态,则它必须是静态的.
否则,它必须是实例,因为不需要锁定一个类实例的状态,并防止其他线程同时与另一个类实例一起工作.

The lock object has to be static, if it locks access to static state.
Otherwise it has to be instance, because there's no need to lock state of one class instance, and prevent other threads to work with another class instance at the same time.

每个人都说该对象必须是只读"的,我没有找到 原因

everyone says that the object has to be "readonly" I didn't found the reason

好吧,不必.这只是最佳做法,可帮助您避免错误.

Well, it doesn't have to be. This is just a best practice, which helps you to avoid errors.

考虑以下代码:

class MyClass
{
    private object myLock = new object();
    private int state;

    public void Method1()
    {
        lock (myLock)
        {
            state = // ...
        }
    }

    public void Method2()
    {
        myLock = new object();
        lock (myLock)
        {
            state = // ...
        }
    }
}

这里Thread1可以通过Method1获取锁,但是将要执行Method2的Thread2将忽略此锁,因为锁对象已更改=>状态可能会损坏.

Here Thread1 can acquire lock via Method1, but Thread2, which is going to execute Method2, will ignore this lock, because lock object was changed => the state can be corrupted.

这篇关于为什么锁对象必须是只读的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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