gpt4 book ai didi

c# - 为什么锁定我们要更改的对象是一种不好的做法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:07 24 4
gpt4 key购买 nike

为什么在下面的代码中使用锁是一种不好的做法,我假设这是一种基于 this SO question here 中答案的不好的做法。

private void DoSomethingUseLess()
{
List<IProduct> otherProductList = new List<IProduct>();
Parallel.ForEach(myOriginalProductList, product =>
{
//Some code here removed for brevity
//Some more code here :)
lock (otherProductList)
{
otherProductList.Add((IProduct)product.Clone());
}
});
}

关于 there 的答案提到这是不好的做法,但他们没有说明原因

注意:请忽略代码的用处,这只是为了示例目的,我知道它根本没有用

最佳答案

来自 C# 语言引用 here :

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

在您的情况下,我会阅读上述指南,认为锁定您将要修改的集合是一种不好的做法。例如,如果您编写了这段代码:

lock (otherProductList) 
{
otherProductList = new List<IProduct>();
}

...那么你的锁就一文不值了。由于这些原因,建议使用专用的 object 变量进行锁定。

请注意,这并不意味着如果您使用您发布的代码,您的应用程序将中断。 “最佳实践”通常被定义为提供在技术上更具弹性的易于重复的模式。也就是说,如果您遵循最佳实践并拥有一个专用的“锁对象”,您就不太可能永远编写损坏的基于lock 的代码;如果您不遵循最佳实践,那么您可能会被一个很容易避免的问题困扰,可能是百分之一。

此外(更一般而言),使用最佳实践编写的代码通常更容易修改,因为您可以减少对意外副作用的警惕。

关于c# - 为什么锁定我们要更改的对象是一种不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24948150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com