The primary use of IDisposable interface

Possible Duplicate:
Proper use of the IDisposable interface

"IDisposable Interface" article tells:

The primary use of this interface is to release unmanaged resources

Why? Why only unmanaged?

Whole my life I thought its PRIMIRALY use is to release ANY resources: managed (connections to DBs, services proxies, etc) and unmanaged (if they are used in application).

PS

I believe there are already questions on this topic, but can't find them.


The underlying connections to db's are not managed, as are file handles and a number of other low-level o/s objects. They are unmanaged. Implementing an IDisposable interface implies that you are not just relying on the garbage collector to release those resources; but you are closing those resources using what ever low-level API that you have available.

Also, I think Eric Lippert's answer (2nd one down) to a similar question is a very good explanation on why you would use IDisposable .


If you read further there is an explanation:

The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

Garbage collector takes care about managed resources. This is why they are managed .

Also, connection resource in your example is not managed resource. .NET connection classes wrap unmanaged resources.


IDisposable.Dispose() is responsible for two things:

  • Releasing unmanaged resources that the object might own
  • Dispose() ing other IDisposable s owned by the object
  • 链接地址: http://www.djcxy.com/p/54468.html

    上一篇: IDisposable究竟需要什么?

    下一篇: IDisposable接口的主要用途