When are C# “using” statements most useful?

强颜欢笑 提交于 2019-12-04 16:46:57

问题


So a using statement automatically calls the dispose method on the object that is being "used", when the using block is exited, right?

But when is this necessary/beneficial?

For example let's say you have this method:

public void DoSomething()
{
    using (Font font1 = new Font("Arial", 10.0f))
    {
        // Draw some text here
    }
}

Is it necessary to have the using statement here, since the object is created in the method? When the method exits, wont the Font object be disposed of anyway?

Or does the Dispose method get run at another time after the method exits?

For example if the method was like this:

public void DoSomething()
{
    Font font1 = new Font("Arial", 10.0f);

    // Draw some text here
}

// Is everything disposed or cleared after the method has finished running?

回答1:


The 'using' statement is most useful when working with unmanaged objects, like database connections.

In this way, the connection is closed and disposed no matter what happens in the code block.

For more discussion, see this article on CodeProject: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx




回答2:


Without using (or manually calling Dispose()), the object will eventually be disposed of, just not at a deterministic time. That is, it can happen straight away, in two days' time, or (in some cases) never.

For things like, say, network connections, you want the connection to close when you're done with it, not "whenever", otherwise it'll idle around hogging up a socket.

Further, for things like mutex locks, you do not want those to be released "whenever", or else deadlock is likely to result.




回答3:


This:

public void DoSomething()
{
    using (Font font1 = new Font("Arial", 10.0f))
    {
        // Draw some text here
    }
}

maps directly to this:

public void DoSomething()
{
    {
        Font font1;
        try
        {
            font1 = new Font("Arial", 10.0f);
            // Draw some text here
        }
        finally
        {
            IDisposable disp = font1 as IDisposable;
            if (disp != null) disp.Dispose();
        }
    }
}

Note the finally block: the object is disposed even if an exception occurs. Also note the extra anonymous scope block: it means that not only is the object disposed, but it goes out of scope as well.

The other important thing here is that disposal is guaranteed to happen right away. It's deterministic. Without a using statement or similar construct, the object would still go out of scope at the end of the method and could then be collected eventually. The resource then would ideally be destroyed so it can be reclaimed by the system. But "eventually" might not happen for a while, and "would ideally" and "will" are very different things.

Therefore, "eventually" isn't always good enough. Resources like database connections, sockets, semaphores/mutexes, and (in this case) GDI resources are often severely limited and need to be cleaned up right away. A using statement will make sure this happens.




回答4:


The using construct enforces deterministic disposal -- i.e. release of resources. In your example above, yes, if you don't employ a "using" statement, the object will be disposed, but only if the recommended disposable pattern (that is, disposing of resources from a class finalizer, if applicable) has been implemented for the class in question (in your example, the Font class). It should be noted, that the using construct can only be used with objects that implement the IDisposable interface. It is the presence of that interface on an object that allows using to "call" the Dispose method.

Additionally, underlying resources will only be released when the garbage collector decides to collect your out-of-scope Font object. A key concept in .Net programming (and most languages with a garbage collector) is that just because an object goes out of scope does not mean that it is finalized/released/destroyed, etc. Rather, the garbage collector will perform the clean-up at a time it determines -- not immediately when the object goes out of scope.

Finally, the using statement "bakes in" a try/finally construct to ensure that Dispose is called regardless of contained code throwing an exception.




回答5:


the "Using" comes into play when a resource needs to be disposed and it implements the IDisposable interface.




回答6:


When the method exits, wont the Font object be disposed of anyway?

No, it will become unreferenced, and thus eligible for garbage collection. Unless something else (e.g. a reference held in another data structure) holds on to a reference.

Or does the Dispose method get run at another time after the method exits?

Yes, in a process not allocating much memory that could be a considerable time after the method has exited.

Garbage Collection is inherently asynchronous and lazy, thus making it a great way to ensure memory is freed, if memory is not too limited; but poor for almost any other resource.




回答7:


It seems very simple to me.

If a class implements IDisposable, then it is almost asking you to please call Dispose on any instance that you create, as soon as you're done with it. This is the pattern I suggest should be used, whenever such an instance is created:

using (var instanceName = new DisposableClass())
{
    // Your code here
}

It's simple, it's clean, and it works for everything except for WCF proxy classes, which are broken. For those, see http://www.iserviceoriented.com/blog/post/Indisposable+-+WCF+Gotcha+1.aspx.




回答8:


Here's what using really does (based on your example)

Font font1 = new Font(...);
try
{
    // code that uses font...
}
finally
{
    if (font1 != null)
        font1.Dispose();
}

So you don't need to worry about exception making your variable not disposed.




回答9:


They are useful in any situation when you want cleanup code to be called on an object deterministically and regardless of exceptions (since a using statement is really just a try/finally).

Most often they are used to clean up unmanaged resources but you can use them however you see fit.




回答10:


It is purely syntactic sugar on top of a try-catch-finally block and a call to the Dispose method. It does not even necessarily define a lexical scope since you can hand it an instance variable. Basically, it makes your code cleaner and easier to maintain.




回答11:


Dispose is called when it exits the using statement because it's explicitly called by that construct. The dispose method isn't called explicitly when the variable goes out of scope (exiting method).

The behavior you MAY observe that looks like that is that usually things that implement IDisposable also call the Dispose method in the classes destructor, and the destructor COULD be called soon after the variable goes out of scope, but not guaranteed. The destructor is invoked by the garbage collector.




回答12:


I like to use them like this:

    static public void AddSampleData(String name)
    {
        String CreateScript = GetScript(String.Format("SampleData_{0}", name));
        using (IDbConnection MyConnection = GetConnection())
        {
            MyConnection.Open();
            IDbCommand MyCommand = MyConnection.CreateCommand();
            foreach (String SqlScriptLine in CreateScript.Split(';'))
            {
                String CleanedString = SqlScriptLine.Replace(";", "").Trim();
                if (CleanedString.Length == 0)
                    continue;

                MyCommand.CommandText = CleanedString;
                int Result = MyCommand.ExecuteNonQuery();
            }
        }
    }

They work great for cases where you don't want to put error checking code only cleans up and passes the error on down. The alternative method would look like this:

    static public void AddSampleData(String name)
    {
        String CreateScript = GetScript(String.Format("SampleData_{0}", name));

        IDbConnection MyConnection = null;
        try
        {
            IDbConnection MyConnection = GetConnection();
            MyConnection.Open();
            IDbCommand MyCommand = MyConnection.CreateCommand();
            foreach (String SqlScriptLine in CreateScript.Split(';'))
            {
                String CleanedString = SqlScriptLine.Replace(";", "").Trim();
                if (CleanedString.Length == 0)
                    continue;

                MyCommand.CommandText = CleanedString;
                int Result = MyCommand.ExecuteNonQuery();
            }
        }
        finally
        {
            if (MyConnection != null
                && MyConnection.State == ConnectionState.Open)
                MyConnection.Close();
        }
    }

And frankly, which method is easier to read? Same thing with forms:

    public void ChangeConfig()
    {
        using (ConfigForm MyForm = new ConfigForm())
        {
            DialogResult ConfigResult = MyForm.ShowDialog();
            if (ConfigResult == DialogResult.OK)
                SaveConfig();
        }

        ConfigForm MyForm = new ConfigForm();
        DialogResult ConfigResult = MyForm.ShowDialog();
        MyForm.Dispose();
        if (ConfigResult == DialogResult.OK)
            SaveConfig();
    }



回答13:


All the answers about deterministic vs. undeterministic and how the using works under the hood are correct.

But to pick your specific sample, don't forget that almost all System.Drawing (GDI+ wrapper) objects also hold references to unmanaged memory, so that you may run into trouble when using those extensively without disposing them properly (where using is the easiest way).




回答14:


I asked a very similar question here:

Resources that have to be manually cleaned up in C#?

And i got a nice piece of advice in the form of:

In general, if something has a Dispose method, you should call it when you've finished with it, or, if you can, wrap it up in a using statement.



来源:https://stackoverflow.com/questions/752581/when-are-c-sharp-using-statements-most-useful

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