General Rule for When to Implement IDisposable

后端 未结 6 1415
南旧
南旧 2020-11-29 12:00

EDIT: This question is a duplicate of What is the difference between managed and native resources when disposing? (.NET) and many others. Please answer the

相关标签:
6条回答
  • 2020-11-29 12:13

    Implement IDisposable when you have a class what wraps an unmanaged resource or when your class has a field that implements IDisposable.

    0 讨论(0)
  • 2020-11-29 12:13

    I normally implement IDisposable every time I need to do a clean up of items. For me this is when writing code that abstracts database/network/filesystems.

    It just marks items ready for the Garbage Collector instead of waiting for it to try do it on its own.

    0 讨论(0)
  • 2020-11-29 12:16

    From MSDN: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

    Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

    0 讨论(0)
  • 2020-11-29 12:16

    IDisposable is one of a programmers main weapons against .Net memory leaks. Whilst the documentation suggests that it should be used for external resources, I make extensive use of IDisposable to release internal resources such as pointers to parent classes.

    It is quite easy to demonstrate the requirement by creating two mutually referential classes i.e. foo and bar. foo refers to bar and vice versa. When foo falls out of scope, the GC sees bar still refers to it so it is not collected (and vice versa). The memory is not collected.

    This is the same style of problem exhibited by EventHandlers where the reference is not released when the form is closed unless it is explicitly released or the WeakEvent model is implemented.

    I would suggest that best practice is to assume a C++ programming model where you clean up after yourself using Dispose unless you are convinced that the GC can work it out for you.

    0 讨论(0)
  • 2020-11-29 12:25

    When you need to release unmanaged resources, implement IDisposable.

    0 讨论(0)
  • 2020-11-29 12:31

    Whenever you alocate resources that must be released, such as files, handles, etc. For example, if you are using Win32 resources (which do not implement IDisposable) you should implement IDisposable to release them.

    0 讨论(0)
提交回复
热议问题