Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?

a 夏天 提交于 2020-01-23 12:29:13

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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




回答6:


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.




回答7:


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.




回答8:


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.



来源:https://stackoverflow.com/questions/3560921/is-it-better-to-use-the-using-statement-in-c-sharp-or-the-dispose-method-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!