How to fix a CA2000 IDisposable C# compiler warning, when using a global cache

后端 未结 3 1194
醉梦人生
醉梦人生 2020-12-20 20:37

CA2000 is a warning regarding the IDisposable interface:

CA2000 : Microsoft.Reliability : In method \'ImportProcessor.GetContext(string)\', call Sys

3条回答
  •  暖寄归人
    2020-12-20 21:03

    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();
            }
        }
    }
    

提交回复
热议问题