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



DocumentStore实现IDisposable。

为什么?我还能如何处置DocumentStore对象?它们是在using块中创建的,我将其放在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;
    }
}

最佳答案

您必须确保沿着任何可能的异常路径放置所有新创建的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(); }
    }
}

CA似乎有内联属性初始化程序存在问题,但是如果将它们分解,这应该可以工作。关键是要确保无论在try块中的什么地方引发异常,都可以清除所有可以处置的新对象。

通过设置临时引用,您在返回之前就不再需要null(docStore1docStore2tempShardedDocumentStore),您可以在finally块中检查它们是否实际上已设置为null,如果没有,则异常发生在某个地方,并且您可以在执行离开此方法之前将其处置。

注意 docStore1docStore2是临时引用,因为它们已添加到Shards集合中。

关于c# - 正确处理: object not disposed along all exception paths的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10125070/

10-13 05:26