C#锁定和代码分析警告CA2002 [英] C# lock and code analysis warning CA2002

查看:67
本文介绍了C#锁定和代码分析警告CA2002的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个启动同步过程的表单,由于种种原因,我一次只允许运行一次同步.因此,我在表单中添加了一个静态的bool字段来指示是否正在进行同步,并添加了一个锁,如果尚未设置该字段,则将该字段设置为true,以便第一个线程可以开始同步,但是当它正在运行所有其他线程时,将尝试启动它将终止.

In my application I have a form that starts synchronization process and for number of reasons I want to allow only one synchronization to run at a time. So I've added a static bool field to my form indicating whether sync is in progress and added a lock to set this field to true if it wasn't already set so that first thread could start synchronization but when it's running every other thread that will try to start it will terminate.

我的代码是这样的:

internal partial class SynchronizationForm : Form
{
    private static volatile bool workInProgress;

    private void SynchronizationForm_Shown(object sender, EventArgs e)
    {
        lock (typeof(SynchronizationForm))
        {
            if (!workInProgress)
            {
                workInProgress = true;
            }
            else
            {
                this.Close();
            }
        }
    }
}

这很好,但是当我在项目上运行代码分析时,我收到以下警告消息:

This is working well but when I run Code Analysis on my project I'm getting the following warning message:

CA2002:Microsoft.Reliability:"SynchronizationForm.SynchronizationForm_Shown(object,EventArgs)"锁定类型"Type"的引用.将其替换为针对具有强同一性的对象的锁.

CA2002 : Microsoft.Reliability : 'SynchronizationForm.SynchronizationForm_Shown(object, EventArgs)' locks on a reference of type 'Type'. Replace this with a lock against an object with strong-identity.

任何人都可以向我解释我的代码有什么问题以及如何改进它以使警告消失.物体具有强身份是什么意思?

Can anyone explain to me what's wrong with my code and how can I improve it to make the warning gone. What does it mean that object has a strong-identity?

推荐答案

错误的是,您正在锁定可以从您的代码随处访问的公共(typeof(SynchronizationForm)),并且是否有其他线程锁定了同一件事你会陷入僵局.通常,最好只锁定私有静态对象:

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) 
{

}

这向您保证只有SynchronizationForm可以拥有该锁.

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

这篇关于C#锁定和代码分析警告CA2002的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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