Close and Dispose - which to call?

2018-12-31 13:40发布

Having read the threads Is SqlCommand.Dispose enough? and Closing and Disposing a WCF Service I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?

标签: .net
7条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 13:53

As usual the answer is: it depends. Different classes implement IDisposable in different ways, and it's up to you to do the necessary research.

As far as SqlClient goes, the recommended practice is to do the following:

using (SqlConnection conn = /* Create new instance using your favorite method */)
{
    conn.Open();
    using (SqlCommand command = /* Create new instance using your favorite method */)
    {
        // Do work
    }
    conn.Close(); // Optional
}

You should be calling Dispose (or Close*) on the connection! Do not wait for the garbage collector to clean up your connection, this will tie up connections in the pool until the next GC cycle (at least). If you call Dispose, it is not necessary to call Close, and since the using construct makes it so easy to handle Dispose correctly, there is really no reason to call Close.

Connections are automatically pooled, and calling Dispose/Close on the connection does not physically close the connection (under normal circumstances). Do not attempt to implement your own pooling. SqlClient performs cleanup on the connection when it's retrieved from the pool (like restoring the database context and connection options).

*if you are calling Close, make sure to do it in an exception-safe way (i.e. in a catch or finally block).

查看更多
余生无你
3楼-- · 2018-12-31 13:53

You DO need to call Dispose()!

Dispose() is for the developer to call, the Garbage Collector calls Finalize(). If you don't call Dispose() on your objects any unmanaged resources that they used won't be disposed until the garbage collector comes around and calls finalize on them (and who knows when that will happen).

This scenario is called Non Deterministic Finalization and is a common trap for .net developers. If you're working with objects that implement IDisposable then call Dispose() on them!

http://www.ondotnet.com/pub/a/oreilly/dotnet/news/programmingCsharp_0801.html?page=last

While there may be many instances (like on SqlConnection) where you call Disponse() on some object and it simply calls Close() on it's connection or closes a file handle, it's almost always your best bet to call Dispose()! unless you plan on reusing the object in the very near future.

查看更多
心情的温度
4楼-- · 2018-12-31 14:01

I want to clarify this situation.

According to Microsoft guidelines, it's a good practice to provide Close method where suitable. Here is a citation from Framework design guidelines

Consider providing method Close(), in addition to the Dispose(), if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose ...

In most of cases Close and Dispose methods are equivalent. The main difference between Close and Dispose in the case of SqlConnectionObject is:

An application can call Close more than one time. No exception is generated.

If you called Dispose method SqlConnection object state will be reset. If you try to call any method on disposed SqlConnection object, you will receive exception.

That said:

  • If you use connection object one time, use Dispose.
  • If connection object must be reused, use Close method.
查看更多
美炸的是我
5楼-- · 2018-12-31 14:06

Typecast to iDisposable, and call dispose on that. That will invoke whatever method is configured as implementing "iDisposable.Dispose", regardless of what the function is named.

查看更多
查无此人
6楼-- · 2018-12-31 14:07

Generally we are facing issue in Close(), Abort() and Dispose() but let me tell you difference among them.

1) ABORT:- I won't suggest to use this because when abort is called the client will delete the connection without telling the server so server will wait for some amount of time (approximately 1 min). If you having bulk request then you can't use abort() because it may caused time out for your limited connection pool.

2) Close:- Close is very good way to closing the connection because when closing the connection it will call server and acknowledge the server to close by that side too.

Here, one more thing to look. In some cases, if error generates then it is not a good way to write code in finally that connection.close() because at that time Communication State will be faulted.

3) Dispose :- It is one type of close but after closing the connection you can not open it again.

So try this way ,

private void CloseConnection(Client client)
    {
        if (client != null && client.State == CommunicationState.Opened)
        {
            client.Close();
        }
        else
        {
            client.Abort();
        }
    }
查看更多
刘海飞了
7楼-- · 2018-12-31 14:14

For SqlConnection, from the perspective of the connection itself, they are equivalent. According to Reflector, Dispose() calls Close() as well as doing a few additional memory-freeing operations -- mostly by setting members equal to null.

For Stream, they actually are equivalent. Stream.Dispose() simply calls Close().

查看更多
登录 后发表回答