为什么会出现这种方法的原因code解析错误CA2000:调用Dispose() [英] Why does this method cause Code Analysis error CA2000: Call Dispose()

查看:407
本文介绍了为什么会出现这种方法的原因code解析错误CA2000:调用Dispose()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建我的项目与微软最小规则code分析集,这让我CA2000此方法:

I'm building my project with the "Microsoft Minimal Rules" code analysis set and it gives me CA2000 on this method:

private Timer InitializeTimer(double intervalInSeconds)
{
    Timer timer = null;

    try
    {
        timer = new Timer { Interval = intervalInSeconds * 1000, Enabled = true };
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }
    catch
    {
         if (timer != null)
         {
             timer.Dispose();
         }
    }
    return timer;
}

此方法只从秒的时间间隔创建一个新的 System.Timers.Timer的。我有运行(一个用于每一秒,每分钟一个,一个,每半小时)三个这样的计时器。也许这是最好有一个定时器,然后检查经过的事件处理一分钟或半小时是否已经过去了,但我不知道,这是在这个时候比较容易,它继承了code和我不想要打破一切呢。

This method just creates a new System.Timers.Timer from an interval in seconds. I have three such timers running (one for every second, one every minute and one every half hour). Maybe it's better to have one timer and check in the elapsed event handler whether a minute or a half hour has passed, but I don't know, this is easier at this time, it's inherited code and I don't want to break everything yet.

这个方法给我臭名昭著

Warning 21  CA2000 : Microsoft.Reliability : In method 'TimerManager.InitializeTimer(double)', call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope.

我现在调用Dispose在渔获物和认为这将是足够的?我也处理所有的定时器类中的自己的IDisposable实现。

Now I AM calling Dispose in the catch and thought this would be enough? I'm also disposing all timers in the class' own IDisposable implementation.

我是什么在这里失踪?

推荐答案

好吧,我编辑这样的:

private Timer InitializeTimer(double intervalInSeconds)
    {
        Timer tempTimer = null;
        Timer timer;
        try
        {
            tempTimer = new Timer();
            tempTimer.Interval = intervalInSeconds * 1000;
            tempTimer.Enabled = true;
            tempTimer.Elapsed += timer_Elapsed;
            tempTimer.Start();
            timer = tempTimer;
            tempTimer = null;
        }
        finally
        {
            if (tempTimer != null)
            {
                tempTimer.Dispose();
            }
        }
        return timer;
    }

这是每CA2000文档,并没有给出一个警告。我曾忽略的对象初始化语法创建它可以不设置临时对象的事实。

This is per the CA2000 docs and it doesn't give a warning. I had overlooked the fact that the object initializer syntax creates a temporary object which may not be disposed.

谢谢你们!

这篇关于为什么会出现这种方法的原因code解析错误CA2000:调用Dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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