C# lock and code analysis warning CA2002

梦想与她 提交于 2019-12-05 05:09:23

What is wrong is that you are locking on something public (typeof(SynchronizationForm)) which is accessible everywhere from your code and if some other thread locks on this same thing you get a deadlock. In general it is a good idea to lock only on private static objects:

private static object _syncRoot = new object();
...
lock (_syncRoot) 
{

}

This guarantees you that it's only SynchronizationForm that could possess the lock.

From the MSDN explanation of the rule

An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object.

Since you can't necessarily predict what locks another AppDomain might take, and since such locks might need to be marshalled and would then be expensive, this rule makes sense to me.

The problem is that typeof(SynchronizationForm) is not a private lock object, which means that any other piece of code could use it to lock on, which could result in deadlock. For example if some other code did this:

var form = new SynchronizationForm();
lock(typeof(SynchronizationForm))
{
    form.SomeMethodThatCausesSynchronizationForm_ShownToBeCalled();
}

Then deadlock will occur. Instead you should delcare a private lock object in the SynchronizationForm class and lock on that instead.

The System.Type object of a class can conveniently be used as the mutual-exclusion lock for static methods of the class.

Source: http://msdn.microsoft.com/en-us/library/aa664735(VS.71).aspx

To add to Doug's answer, what you have here is a locking mechanism which should only be used in static methods, being used in an instance method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!