避免在C#中使用"using"关键字进行多次处置的最佳实践 [英] Best practice to avoid multiple disposals with the `using` keyword in C#

查看:109
本文介绍了避免在C#中使用"using"关键字进行多次处置的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当变量是IDisposable时,我们使用using关键字来管理处置.但是,如果我们在方法中返回该值,应该两次出现using吗?

When a variable is IDisposable, we have the using keyword to manage the disposal. But what if we return the value in a method, should we have using twice?

StringContent stringToStringContent(string str)
{
    using (StringContent content = new StringContent(str))
    {
        return content;
    }
}

void logStringContent()
{
    using (StringContent content = stringToStringContent("test"))
    {
        Debug.WriteLine(content.ToString());
        return;
    }
}

在上面的示例中,我只有1个new,但对于同一件事我只有2个using.所以我觉得这是不平衡的.更好:

In this example above, I only have 1 new but I have 2 using for the same thing. So I feel it's unbalanced. Is it better to:

a)同时保留using,并且语言/编译器知道它的工作来避免重复处理?

a) keep both using, and the language/compiler knows its job to avoid double-disposal?

b)仅将usingnew放在一起,在其他情况下不需要吗?:

b) keep only using with new together, and no need in other cases?:

void logStringContent()
{
    StringContent content = stringToStringContent("test");
    Debug.WriteLine(content.ToString());
    return;
}

c)不返回时仅保留using,返回时无需保留?:

c) keep only using when you don't return, and no need when you return?:

StringContent stringToStringContent(string str)
{
    return new StringContent(str);
}

我唯一能感觉到的是b)不是正确的答案,因为它不适用于此处描述的问题:.NET HttpClient在多个请求后挂起(除非Fiddler处于活动状态)

The only thing I can feel is that b) isn't the correct answer, because it wouldn't work for issues like the one described here: .NET HttpClient hangs after several requests (unless Fiddler is active)

推荐答案

我认为c在这里是正确的答案-您正在从该方法返回(对)对象的引用-已经存在是没有道理的在您退还该对象之前,请先将其丢弃.例如,File.OpenRead不会处理它返回的流,对吗?

I think c is the right answer here - you're returning (a reference to) an object from the method - it makes no sense to have already disposed of that object before you return it. For example, File.OpenRead wouldn't dispose of the stream that it returns, would it?

最好在方法文档中指出调用者负责处置对象.同样,某些方法接受一种可抛弃的类型,并指出调用者则不应自己处置该对象.在这两种情况下,实际上都有责任转移,以正确处置该物体.

It would be a good idea to indicate in the method documentation that the caller takes responsibility for disposing of the object though. Likewise, some methods accept a disposable type and state that the caller then shouldn't dispose of the object themselves. In both case there's effectively a transfer of responsibility for disposing of the object properly.

这篇关于避免在C#中使用"using"关键字进行多次处置的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆