非托管资源和Dispose()

问题描述:

我正在阅读一些有关 Dispose()方法的文章,发现应该从 Dispose()方法(或finalize()方法)和非托管资源中显式释放非托管资源.文章说文件句柄和数据库连接对象是非托管资源的示例.谁能解释为什么这些都是不受管理的,如果没有在Dispose()中正确处理,会发生什么?我不知道文件句柄是什么.它们存在于何处?

I was reading some articles about Dispose() method and found that unmanaged resources should be freed explicitly from Dispose() method (or finalize() method) and the article says file handles and database connection objects are examples of unmanaged resources. Can anyone explain why those are unmanaged and what happens if not handled properly in Dispose()? I have no idea about what a file handle is. Where do they exist?

在这种情况下,最容易想到的是这样:

In this context it's perhaps easiest to think of it like this:

  • 非托管资源是您通过执行Windows API调用并返回唯一的另一种资源是内存.如果它由.Net分配,则将自动对其进行管理.(请注意,有多种方法可以使用Windows API分配内存;这被视为非托管资源.)

    The only other kind of resource is memory. This is managed automatically if it was allocated by .Net. (Note that there are ways to allocate memory using the Windows API; this counts as an unmanaged resource.)

    例如, FileStream 类调用Windows API打开文件,为此 FileStream 在内部保留文件句柄.该文件句柄表示必须在某个时候释放的非托管资源.

    For example, the FileStream class calls the Windows API to open a file, for which FileStream keeps a file handle internally. That file handle represents an unmanaged resource that must be freed at some point.

    FileStream 使用Windows API函数

    FileStream uses the Windows API function CreateFile() behind the scenes. It is the handle returned from CreateFile which represents an unmanaged resource.

    如果不释放这些句柄,它们将在程序执行期间保持分配状态,但是所有具有非托管资源的.Net类都将提供 Finalizer (请参见下文),以确保它们通常会在某个时候被释放.

    If you don't free those handles, they will remain allocated for the duration of the program, but all .Net classes that have an unmanaged resource provide a Finalizer (see below) to make sure that they will normally be freed at some point.

    (但是,如果您正在编写自己的文件处理类,却根本忘记在任何地方释放文件句柄,则文件将保持打开状态,直到程序退出.)

    (But if you were writing your own file handling class and forgot to free the file handle anywhere at all, the file would remain open until your program exited.)

    通常,此类不受管理的资源将在两个位置释放:

    Normally such unmanaged resources will be freed in two places:

    • Dispose()方法.这应该是处置非托管资源的常规方法.

    • The Dispose() method. This should be the normal way that you dispose unmanaged resources.

    Finalizer .这是最后一种机制.如果一个类具有终结器,则该类将在清理死对象时由垃圾回收器调用.如果程序员忘记调用Dispose(),则任何具有非托管资源的类都应具有终结器以进行清理.

    The Finalizer. This is a last-resort mechanism. If a class has a finalizer it will be called by the Garbage Collector when it cleans up a dead object. Any class which has an unmanaged resource should have a finalizer to clean up if the programmer forgets to call Dispose().

    这有点简化,但我希望它可以帮助您理解它.

    This is somewhat of a simplification, but it will help you understand it I hope.

    有关完整的详细信息,请参见此MSDN文章在处理模式上.

    For full details, see this MSDN article on the Dispose Pattern.