Why call Dispose()? Memory leak won't occur?

2019-02-04 16:09发布

Edit: My question isn't getting the main answer that I was looking for. I wasn't clear. I would really like to know two things:

  1. Can NOT calling Dispose() cause memory leaks?
  2. What's the worst thing that can happen if you have a large program and never call Dispose() on any of your IDisposable objects?

I was under the impression that memory leaks could occur if Dispose() isn't called on IDisposable objects.

Per the discussion on this thread, my perception was incorrect; a memory leak will NOT occur if Dispose() isn't called.

Why ever bother calling Dispose() then? Is it just to free the resource immediately, instead of sometime later? What's the worst thing that can happen if you have a large program and never call Dispose() on any of your IDisposable objects?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-04 16:46

Not calling Dispose will not ever (*see note 2 on wrong implementation) cause traditional "memory leak" (memory is never freed till end of the process).

The "only" thing that will happen in relation to memory is it will be freed in non-deterministic moment in the future.

One interesting case of non Dispose objects is when very small managed objects hold large amounts of unmanaged memory (i.e. allocated with some flavor of Win32 memory management functions i.e. HeapAlloc ). In this case managed memory manager may not be able to detect memory pressure properly to trigger Gen2 GC and (especially in case of x86 - 32bit process) it may prematurely fail to allocate managed memory for your process. The other issue in this case is fragmentation of address space by "waiting for GC to be de-allocated" (again mostly in x86 case) - when smaller chunks of native memory are allocated with some relatively large space between them preventing allocation of large blocks needed for managed memory management.

Notes:

  1. This answer explicitly talks about true memory leaks/memory allocation issues cased by not disposing IDisposable object managing memory. While it is true that there are no "true memory leaks" caused by such practice most people will consider growing memory usage as memory leak (similar to storing large amount of objects in static list/dictionary for lifetime of an application).
  2. One can create object that manages native memory and incorrectly implements IDisposable pattern. In this case it is possible to really leak native memory (irrespective of calling Dispose).
  3. In most cases objects that implement IDisposable don't managed memory at all. For most practical C# programs native resources managed by such objects are handles for system resources like files, bitmaps, fonts, synchronization objects or COM native objects. Not disposing them in timely manner will cause other issues.

Dispose all objects properly. There is no excuse not to.

查看更多
登录 后发表回答