I have read a lot about finalizer and IDisposable
in C#. As I finally become clear from this monstrous confusion over finalizer and IDisposable
, suddenly, out of nowhere, there is this SafeHandle thing.
My belief is completely shaken again. What am I supposed to use?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.
SafeHandle is only useful when dealing with Win32 Interop calls. In Win32, most things are represented by "handles". This includes Windows, Mutexes, etc. So the .NET SafeHandle uses the disposable pattern to ensure the Win32 handle is properly closed.
So if you are using Win32 Interop calls and getting back Win32 handles, then use SafeHandle. For your own objects, you would stick with IDisposable and a finalizer.
You can/should use SafeHandle for any unamanaged resource which can be represented as IntPtr, i.e. Win32 handles, memory allocated by unmanaged code and so on. When SafeHandle isn't suitable, but you still need to handle unmanaged reources, consider making your own SafeHandle-like class inheriting from CriticalFinalizerObject.
In all other cases (i.e. handling managed resources) implement IDisposable. In most cases you won't need finalizer, most managed resources will be unavailable when finalizer is called, so there would be nothing to do there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With