When to dispose and why?

后端 未结 12 1063
臣服心动
臣服心动 2020-12-10 14:20

I asked a question about this method:

// Save an object out to the disk
public static void SerializeObject(this T toSerialize, String filename)
{
           


        
12条回答
  •  臣服心动
    2020-12-10 14:35

    You are correct that for properly written code the GC will eventually clean up the native resources. The object will have a finalizer, and during finalization will free up the necessary native resources.

    However when this happens is very non-deterministic. Additionally it's a bit backwards because you're using the GC which designed to handle managed memory as a means to manage native resources. This leads to interesting cases and can cause native resources to stay alive much longer than anticipated leading to situations where

    • Files are open long after they are no longer used
    • Resource handles can run out because the GC doesn't see enough memory pressure to force a collection and hence run finalizers

    The using / dispose pattern adds determinism to the cleanup of native resources and removes these problems.

提交回复
热议问题