Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do IDisposable objects get disposed of if the program is shut down unexpectedly?

What happens if the program exits unexpectedly (either by exception or the process is terminated)? Are there any situations like this (or otherwise) where the program will terminate, but IDisposable objects won't be properly disposed of?

The reason I'm asking is because I'm writing code that will communicate with a peripheral, and I want to make sure there's no chance it will be left in a bad state.

like image 293
JSideris Avatar asked Dec 25 '15 15:12

JSideris


People also ask

How do you Dispose of IDisposable?

If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

What does it mean when an object implements IDisposable?

Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.

Do you need to Dispose C#?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope. Yes, you should dispose of objects that implement IDisposable.


2 Answers

If the cause is an exception and thrown from within a using block or a try catch finally block, it will be disposed as it should. If it is not catched by a using block it is not disposed automatically (like it doesn't do when the application closes properly).

A sample:

IDisposable d1 = new X();  using (IDisposable d2 = new X()) {     throw new NotImplementedException(); }  d1.Dispose(); 

d1 is not disposed, d2 usually is. Some types of exceptions may prevent handling of using blocks and also some program crashes. If the cause is a power failure or system crash, there is nothing you can do either of course.

like image 167
Patrick Hofman Avatar answered Sep 27 '22 18:09

Patrick Hofman


If the program quits unexpectedly (for example you kill the process) there are absolutely no guarantees that the IDisposable.Dispose method will be called. You'd better not rely on it for such events. The Dispose method must be called manually by your code, it's not something that the CLR will call automatically for you.

like image 45
Darin Dimitrov Avatar answered Sep 27 '22 17:09

Darin Dimitrov