C#中使用[using]语句好还是使用[dispose]方法好?这是否适用于外部 (COM) 对象?

发布于 2024-09-16 00:38:15 字数 534 浏览 5 评论 0原文

完成对象后,使用 using 指令或 dispose 指令哪个更好?

 using(FileStream fileStream = new FileStream(
            "logs/myapp.log",
            FileMode.Open,
            FileAccess.Read,
            FileShare.ReadWrite))
        {
            using(StreamReader streamReader = new StreamReader(fileStream))
            {
                this.textBoxLogs.Text = streamReader.ReadToEnd();
            }
        }

另一方面,当我处理 System.Net.Mail 时,我被告知需要对该对象进行 Dispose() 来释放任何杂散锁。

有没有一致的指导?我如何判断在给定情况下对于给定对象什么更合适?

What is better, the using directive, or the dispose directive when finished with an object?

 using(FileStream fileStream = new FileStream(
            "logs/myapp.log",
            FileMode.Open,
            FileAccess.Read,
            FileShare.ReadWrite))
        {
            using(StreamReader streamReader = new StreamReader(fileStream))
            {
                this.textBoxLogs.Text = streamReader.ReadToEnd();
            }
        }

On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.

Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

埋葬我深情 2024-09-23 00:38:15

using 语句(非指令)涉及在finally 块中隐式调用Dispose()。所以这里不存在矛盾。你能链接到该讨论吗?

官方定义
使用 (x) { ... }

尝试...最后 if (x != null) x.Dispose(); }

什么更好?

从符号的角度来看,using() { } 块。从技术上讲,它们是相同的。

The using statement (not directive) involves an implicit call to Dispose(), in a finally block. So there is no contradiction here. Can you link to that discussion?

The official definition of
using (x) { ... }
is
try ... finally if (x != null) x.Dispose(); }

What is better?

From a notational perspective, the using() { } block. Technically they are the same.

微暖i 2024-09-23 00:38:15

除了在 Dispose() 的另一个实现中(例如在您创建的实现了IDisposable),当您可以将对象包装在 using 块中时。 using 块将对象的创建和处置放在 try/catch/finally 块中,以几乎保证对象将被正确处置。

编译器比我可靠。或者你。 =)

MSDN 记录了using 语句并调用您可以在其中获取 C# 语言规范,您可以在其中查看第 8.13 节“The using statements”(至少在 v4.0 参考中是 8.13)给出了 using 语句以及如何使用它的全面解释。第五段给出以下内容:

using 语句被翻译成
三部分:获取、使用、
处理。资源的使用情况是
隐式包含在 try 语句中
其中包括一个finally子句。这
finally 子句处理了
资源。如果一个空资源是
已获取,则不会调用 Dispose
已完成,并且不会引发异常。

There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.

The compiler is more reliable than me. Or you. =)

MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:

A using statement is translated into
three parts: acquisition, usage, and
disposal. Usage of the resource is
implicitly enclosed in a try statement
that includes a finally clause. This
finally clause disposes of the
resource. If a null resource is
acquired, then no call to Dispose is
made, and no exception is thrown.

始终不够 2024-09-23 00:38:15

这是同样的事情。用法很简单,如果您创建对象并仅在一种方法中使用它,则使用 using。如果您需要在方法调用之外保持它的活动状态,那么您必须使用 Dispose()。

COM 对象的运行时可调用包装器没有 Dispose() 方法。

It's the same thing. Usage is simple, if you create the object and use it in only one method then use using. If you need to keep it alive beyond the method call then you have to use Dispose().

The runtime callable wrappers for COM objects don't have a Dispose() method.

东风软 2024-09-23 00:38:15
using(foo) 
{
    foo.DoStuff();
}

只是语法糖:

try
{
    foo.DoStuff();
}
finally
{
    if(foo != null)
        foo.Dispose();
}

所以我不确定争论从何而来。 using 块会调用 dispose。大多数人更喜欢在可能的情况下使用块,因为它们对于正在发生的事情更清晰、更清晰。

using(foo) 
{
    foo.DoStuff();
}

is just syntactic sugar for this:

try
{
    foo.DoStuff();
}
finally
{
    if(foo != null)
        foo.Dispose();
}

So I'm not sure where the debate comes from. using blocks do call dispose. Most people prefer using blocks when possible as they are cleaner and clearer as to what is going on.

情域 2024-09-23 00:38:15

只要对象的生命周期在代码块内,就使用 using,如果您的对象需要长期存在,例如在异步调用后释放,则需要手动调用 处置

using 块比您记住对 Dispose 的调用要好得多,因为执行可能会留下代码块。

As long as the lifetime of the object is within a block of code, use using, if your object needs to be long lived, for example to be disposed after an asynchronous call you need to manually call Dispose.

A using block is way better than you of remembering the call to Dispose in all possible and impossible ways execution can leave a block of code.

↙温凉少女 2024-09-23 00:38:15

退出时使用调用 Dispose。使用更好,因为它可以确保调用 dispose。

using calls Dispose upon exit. using is better because it assures calling dispose.

秋千易 2024-09-23 00:38:15

当到达块末尾时,using 块会自动调用 Dispose()

using blocks automatically call Dispose() when the end of the block is reached.

一绘本一梦想 2024-09-23 00:38:15

在任何地方都可以使用“using 语句”,这是一个非常重要的原因。

如果通过 using 语句包装的代码抛出异常,您可以确定“using 对象”将被处置。

There is one really important reason to use the "using statement" anywhere you can.

If the code that wrapped via using statement threw an exception, you could be sure that the "using object" would be disposed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文