6

CA2000 は、IDisposable インターフェイスに関する警告です。

CA2000 : Microsoft.Reliability: メソッド 'ImportProcessor.GetContext(string)' で、オブジェクト 'c' へのすべての参照が範囲外になる前に、オブジェクト 'c' で System.IDisposable.Dispose を呼び出します。

私のメソッドは、次のようにコンテキストのキャッシュを保存するために使用されます。

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()このコンパイラ警告を修正するステートメントをどこで使用しますか?

contextCache私の外部クラスは、実際には、独自の実装で内容を反復して破棄します。私はそれを抑制すべきですか、それともこの警告を正しく取り除く方法はありますか?

4

3 に答える 3

6

ここでCA2000が不満を言っているのは、変数をキャッシュに追加しようとしているときに例外が発生した場合、変数が破棄されていない状態で「孤立」する可能性があるということです。この問題に完全に対処するには、次のようにtry / catchを追加します(newContext変数は、CA2000が修正を検出できるようにするためにのみ使用されます)。

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

個人的には、この種のことはほとんどの場合、ややばかげたやり過ぎだと思いますが、ymmv ...

于 2011-07-14T12:43:33.157 に答える