Catastrophic failures within a “using” statement i.e. using(var a= new stream()) and a.Something() throws an exception

StackOverflow https://stackoverflow.com/questions/10745829

Question

So I understand that at the end of a using block statement, the dispose method is called.

What happens if I use a 'using(var a = new Stream()) { a.SomethingThrowsAnException() }'

Does the stream just still go through he dispose method?

I wrote a class that implements IDisposable, and it is mission critical I do not lose what's in memory, so I was planning on serializing the data if something catastrophic happens i.e. I have a custom stream like object I am using.

Any suggestions?

Thanks.

Was it helpful?

Solution

Yes. The using block compiles down to this:

var a = new Stream();
try
{
     a.SomethingThrowsAnException();
}
finally
{
     a.Dispose();
}

OTHER TIPS

I think there may be a situation in which the finally clause ends up executed by a different thread (I have a separate question posted on this issue). It can matter because some operations, such as lock.release, need to occur on the same thread that did the lock.acquire. I'm not sure precisely what causes this, or how to delay the thread termination to ensure that a.Dispose occurs on the thread that did the original new operation...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top