Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# use IDisposable or SafeHandle?

Tags:

c#

idisposable

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?

like image 494
ill mg Avatar asked Oct 18 '11 03:10

ill mg


People also ask

What C is used for?

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 ...

Is C language easy?

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 in C language?

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.

What is C full form?

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.


2 Answers

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.

like image 173
CodeNaked Avatar answered Sep 24 '22 15:09

CodeNaked


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.

like image 34
Konstantin Oznobihin Avatar answered Sep 25 '22 15:09

Konstantin Oznobihin