c# - Why is it a bad practice to lock the object we are going to change? -
Why is it a bad practice to use lock as the following code, I'm assuming it's a bad one Practice is in the answer
Private Zero DoSomethingUseLess () {List & lt; IProduct & gt; OtherProductList = New List & lt; IProduct & gt; (); Parallel.ForEach (myOriginalProductList, product = & gt; {// some code has been removed for summarizing / some other code here :) Lock (Other product list) {otherProductList.Add ((IProduct) Product. ); }}); } In the answer it is remarkable that this is bad behavior, but they do not say why
Note: Please use utility Ignore the code, it's just for example purpose and I know that it is not useful at all.
Language reference from C #:
In general, avoid locking on a public type, or example beyond the control of your code. , lock (this) , lock (typef (mfofip)) , and lock ("mylock") violation of this guideline : lock (this) is a problem if the example can be accessed publicly. lock (typeof (MyType)) is the problem if MyType is publicly accessible. lock ("myLock") is a problem, because there will be another code in the process using the same string, share the same lock the most Good practice is to define a private object to lock, or to keep general data safe in all instances, a personal static object variable.
In your case, I read the above guidance as saying that locking the collection will change you bad practice. For example, if you wrote this code:
lock (other product list) {otherProductList = new list & lt; IProduct & gt; (); } ... then your lock will be unusable. For these reasons, a dedicated object variable has been recommended for locking. Keep in mind that this does not mean that your application will be breaking if the code you post is "best practice" usually to provide easily repetitive patterns These are the more technically flexible ones that are, if you follow the best practice and do a dedicated "lock object", then you ever broken lock Not likely to write a rated code Tempt ye are; If you do not follow the best practice, perhaps in a hundred times, you will have to face an easily preserved problem. In addition to this (and more commonly), the code is usually more easily modified using the best practices, because you can be less alert than unexpected side effects.
Comments
Post a Comment