使用全局缓存时如何解决CA2000 IDisposable C#编译器警告 [英] How to fix a CA2000 IDisposable C# compiler warning, when using a global cache

查看:196
本文介绍了使用全局缓存时如何解决CA2000 IDisposable C#编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CA2000是有关IDisposable接口的警告:

CA2000 is a warning regarding the IDisposable interface:

CA2000:Microsoft.可靠性:方法中 'ImportProcessor.GetContext(string)',调用System.IDisposable.Dispose 在对对象'c'的所有引用都超出范围之前.

CA2000 : Microsoft.Reliability : In method 'ImportProcessor.GetContext(string)', call System.IDisposable.Dispose on object 'c' before all references to it are out of scope.

我的方法用于存储上下文的缓存,如下所示:

My method is used to store a cache of context like so:

public class RegionContext : IDisposable { /* Implement Dispose() here */ } 

private Dictionary<string, RegionContext> contextCache = new ..... ();

public RegionContext GetContext(string regionCode)
{
    RegionContext rc = null;

    if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
    {
        rc = new RegionContext(regionCode);
        this.contextCache.Add(regionCode.ToUpper(), rc);
    }

    return rc;
}

您将在何处使用用于修复此编译器警告的using()语句?

Where would you use the using() statement that fixes this compiler warning?

我的外部类实际上在自己的实现中迭代并处理contextCache中的内容.我应该抑制它,还是有办法正确消除此警告?

My outer class actually does iterate and dispose of the contents in the contextCache in its own implementation. Shall I suppress it, or is there a way to correctly get rid of this warning?

推荐答案

只要您具有IDisposable的返回值并且不处理该方法引发异常的情况,此CA2000警告就会出现.在这种情况下,调用方不会获得您对象的有效实例,因此无法处置它.因此,您必须这样做.

This CA2000 warning comes up any time you have a return value that's IDisposable and don't handle the case where the method throws an exception. In that instance, the caller won't get a valid instance of your object, so it has no way to dispose it. Therefore you have to.

我假设如果成功将其从缓存中拉出,则您将不希望处置该对象.在这种情况下,您需要执行以下操作以确保在所有情况下都可以丢弃您可能在本地创建的对象:

I assume that you won't want to dispose the object if you pull it out of your cache successfully. In that case, you would need to do something like this to make sure the object you might create locally gets disposed in all cases:

public RegionContext GetContext(string regionCode)
{
    RegionContext temp = null;
    RegionContext rc = null;

    try
    {
        if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
        {
            temp = new RegionContext(regionCode);
            this.contextCache.Add(regionCode.ToUpper(), temp);

            rc = temp;
            temp = null;
        }

        return rc;
    }
    finally 
    {
        if ( temp != null ) 
        {
             temp.Dispose();
        }
    }
}

这篇关于使用全局缓存时如何解决CA2000 IDisposable C#编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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