为什么锁定在一个公开的对象是一个坏主意

编程入门 行业动态 更新时间:2024-10-26 03:21:50
本文介绍了为什么锁定在一个公开的对象是一个坏主意的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好吧,我用锁了不少,但我从来没有过这种情况。我有一个包含用于修改同一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.

更多推荐

为什么锁定在一个公开的对象是一个坏主意

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

发布评论

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

>www.elefans.com

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