为什么锁定在一个公开的对象是一个坏主意 [英] Why Locking On a Public Object is a Bad Idea

查看:95
本文介绍了为什么锁定在一个公开的对象是一个坏主意的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我用锁了不少,但我从来没有过这种情况。我有一个包含用于修改同一MSACCESS数据库代码两种不同类型:

Ok, I've used locks quite a bit, but I've never had this scenario before. I have two different classes that contain code used to modify the same MSAccess database:

public class DatabaseNinja
{
    public void UseSQLKatana
    {
        //Code to execute queries against db.TableAwesome
    }
}

public class DatabasePirate
{
    public void UseSQLCutlass
    {
        //Code to execute queries against db.TableAwesome
    }
}

这是一个问题,因为事务数据库不能并行地执行,并且这些方法(UseSQLKatana和UseSQLCutlass)由不同的线程调用。

This is a problem, because transactions to the database cannot be executed in parallel, and these methods (UseSQLKatana and UseSQLCutlass) are called by different threads.

在我的研究,我看到它是的不好的做法,使用公共对象作为锁对象让我怎么锁定这些方法,所以它们不共同经营?答案是简单地在同一类的这些方法? (那其实是我真正的代码没有那么简单)

In my research, I see that it is bad practice to use a public object as a lock object so how do I lock these methods so that they don't run in tandem? Is the answer simply to have these methods in the same class? (That is actually not so simple in my real code)

推荐答案

嗯,首先,你可以创建一个三等:

Well, first off, you could create a third class:

internal class ImplementationDetail
{
    private static readonly object lockme = new object();
    public static void DoDatabaseQuery(whatever)
    {
        lock(lockme)
             ReallyDoQuery(whatever);
    }
}

和现在UseSQLKatana和UseSQLCutlass调用ImplementationDetail.DoDatabaseQuery。

and now UseSQLKatana and UseSQLCutlass call ImplementationDetail.DoDatabaseQuery.

其次,你可以决定不用担心,并锁定一个目标,这两种类型的可见。的主要原因,以避免,这是因为它变得难以推理谁被锁定的对象,而难以防止敌对部分信任的代码恶意锁定的对象。如果你不关心任何缺点,那么你不必盲从的方针。

Second, you could decide to not worry about it, and lock an object that is visible to both types. The primary reason to avoid that is because it becomes difficult to reason about who is locking the object, and difficult to protect against hostile partially trusted code locking the object maliciously. If you don't care about either downside then you don't have to blindly follow the guideline.

这篇关于为什么锁定在一个公开的对象是一个坏主意的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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