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

后端 未结 3 1192
醉梦人生
醉梦人生 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:09

    What CA2000 is complaining about here is that the variable could be "orphaned" in an undisposed state if there's an exception while attempting to add it to the cache. To address the problem thoroughly, you could add a try/catch as follows (the newContext variable is used only so that CA2000 can detect the fix):

    public RegionContext GetContext(string regionCode)
    {
        RegionContext rc = null;
        if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
        {
            RegionContext newContext = new RegionContext(regionCode);
            try
            {
                this.contextCache.Add(regionCode.ToUpper(), newContext);
            }
            catch
            {
                newContext.Dispose();
                throw;
            }
    
            rc = newContext;
        }
    
        return rc;
    }
    

    Personally, I find this sort of thing to be somewhat ridiculous overkill in most cases, but ymmv...

提交回复
热议问题