正确的处理方式:对象未沿所有异常路径放置

Bob*_*orn 5 c# dispose idisposable ca2000 ravendb

我收到第84行和第85行的消息(两个,使用行堆叠):

CA2000:Microsoft.Reliability:在方法'RavenDataAccess.GetRavenDatabase()'中,对象'<> g_ initLocal9'未沿所有异常路径放置.在对对象'<> g _initLocal9'的所有引用都超出范围之前,调用System.IDisposable.Dispose.

DocumentStore实现了IDisposable.

为什么?我还能如何处置DocumentStore对象?它们是在一个使用块中创建的,我将它们放在我的catch块中.该如何修复?

private static IDocumentStore GetRavenDatabase()
{
    Shards shards = new Shards();

    try
    {
        using (DocumentStore docStore1 = new DocumentStore { Url = ConfigurationManager.AppSettings["RavenShard1"] })  // Line 84
        using (DocumentStore docStore2 = new DocumentStore { Url = ConfigurationManager.AppSettings["RavenShard2"] })  // Line 85
        {
            shards.Add(docStore1);
            shards.Add(docStore2);
        }

        using (ShardedDocumentStore documentStore = new ShardedDocumentStore(new ShardStrategy(), shards))
        {
            documentStore.Initialize();

            IndexCreation.CreateIndexes(typeof(RavenDataAccess).Assembly, documentStore);

            return documentStore;
        }
    }
    catch
    {
        shards.ForEach(docStore => docStore.Dispose());

        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*Jim 2

您必须确保沿着任何可能的异常路径处置所有新创建的 Disposable 对象。见下文:

private static IDocumentStore GetRavenDatabase()
{
    Shards shards = new Shards();
    DocumentStore docStore1 = null;
    DocumentStore docStore2 = null;

    ShardedDocumentStore shardedDocumentStore = null;
    ShardedDocumentStore tempShardedDocumentStore = null;

    try
    {
        docStore1 = new DocumentStore();
        docStore1.Url = ConfigurationManager.AppSettings["RavenShard1"];
        docStore2 = new DocumentStore();
        docStore2.Url = ConfigurationManager.AppSettings["RavenShard2"];

        shards.Add(docStore1);
        shards.Add(docStore2);

        tempShardedDocumentStore = new ShardedDocumentStore(new ShardStrategy(), shards);
        tempShardedDocumentStore.Initialize();

        IndexCreation.CreateIndexes(typeof(RavenDataAccess).Assembly, tempShardedDocumentStore);

        docStore1 = null;
        docStore2 = null;

        shardedDocumentStore = tempShardedDocumentStore;
        tempShardedDocumentStore = null;

        return shardedDocumentStore;
    }
    finally
    {
        if (tempShardedDocumentStore != null) { tempShardedDocumentStore.Dispose(); }
        if (docStore1 != null) { docStore1.Dispose(); }
        if (docStore2 != null) { docStore2.Dispose(); }
    }
}
Run Code Online (Sandbox Code Playgroud)

CA 似乎对内联属性初始值设定项有问题,但如果您将它们分解出来,这应该可以工作。关键是要确保无论 try 块中的何处抛出异常,所有可以处理的新对象都会被清除。

通过设置临时引用,您不再需要在返回之前nulldocStore1、、docStore2tempShardedDocumentStore),您可以检查finally块以查看它们是否实际上被设置为null,如果没有,则在某处发生异常,您可以处理它们在执行离开此方法之前。

请注意 docStore1docStore2是添加到Shards集合中时的临时引用。