Good samples of using Finalizers in C#

后端 未结 2 1823
深忆病人
深忆病人 2020-12-31 10:13

When I read a few articles about memory management in C#, I was confused by Finalizer methods.

There are so many complicated rules which related with them. For inst

2条回答
  •  旧巷少年郎
    2020-12-31 10:40

    There is an exhaustive discussion of Finalizer usage, with examples, here. Link courtesy of @SLaks at a related answer.

    See also here for a more concise summary of when you need one (which is "not very often").

    There's a nice prior answer here with another good real-world example.

    To summarize with a pertinent extract:

    Finalizers are needed to guarantee the release of scarce resources back into the operating system like file handles, sockets, kernel objects, etc.

    For more correct real-world examples, browse around affected classes in the .Net Framework this MSDN search:

    http://social.msdn.microsoft.com/Search/en-US?query=%22.Finalize%22&ac=8

    One valid reason I can think of when you might need to use a finalizer is if you wrap a third-party native code API in a managed wrapper, and the underlying native code API library requires the timely release of used operating system resources.

提交回复
热议问题