gpt4 book ai didi

c# - 正确的处理方式 : object not disposed along all exception paths

转载 作者:太空狗 更新时间:2023-10-29 23:25:19 26 4
gpt4 key购买 nike

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

CA2000 : Microsoft.Reliability : In method 'RavenDataAccess.GetRavenDatabase()', object '<>g_initLocal9' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g_initLocal9' before all references to it are out of scope.

DocumentStore 实现了 IDisposable。

为什么?我还能如何处理 DocumentStore 对象?它们是在 using block 中创建的,我在 catch block 中处理它们。这应该如何解决?

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 block 中的哪个位置抛出异常,都可以清除所有可以处理的新对象。

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

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com