What are the rules for when dispose() is required?

前端 未结 4 1356
清歌不尽
清歌不尽 2021-01-13 08:46

Although I have been coding for some time, I\'m really just barely into what I would call an intermediate level coder. So I understand the principle of dispose(), which is

4条回答
  •  野的像风
    2021-01-13 09:32

    The garbage collector (GC) guarantees that managed memory resources that are no longer used are released before the memory limit is reached.

    Let's break that down:

    managed: Loosely, this means resources entirely within .NET/CLR. Memory allocated by non-.NET C++ libraries, for example, are not released by the GC.

    memory: The GC only provides a guarantee on memory usage. Many other resource types exist, such as file handles. The GC has no logic to ensure file handles are released expediently.

    no longer used: This means that all variables with a reference to that memory have ended their lifetime. As Eric Lippert explained, lifetime != scope.

    before the memory limit is reached: The GC monitors "memory pressure" and makes sure to release memory when needed. It uses a bunch of algorithms to decide when it is most efficient to do this, but it's important to note that the GC decides when to release resources all on its own (nondeterministically to your program).


    This leaves us with several scenarios when relying on the GC is not appropriate:

    • The object references unmanaged resources (including referencing a managed object that references an unmanaged resource).
    • The object references a resource other than memory that must be released.
    • The object references a resource that must be released at a specific point in the code (deterministically).

    In any of these cases, the object should implement IDisposable to handle resource cleanup.

    Any object instantiated that implements IDisposable must be cleaned up by either calling Dispose or using the using block (which takes care of calling Dispose for you).

提交回复
热议问题