Reputation: 307
I have a web app (asp.net mvc 4) that uses IDisposable in another project in the solution. It all compiles and runs fine from visual studio (2012) but when using the browser to run the web app (using IIS 8 Express) an exception is throw.
My sealed class that uses IDisposable is in a using statement and the Dispose() method is called before any code in the using braces is reached i.e.
using (MySealedClass msc = new MySealedClass())
{
//Code doesn't reach here. Dispose() is called beforehand
//My code here . . .
}
The constructor and it's dependent are:
private readonly IList<IntPtr> _intPtrList;
public MySealedClass()
{
_intPtrList = new List<IntPtr>();
}
and so I don't think there should be any problem there. To test this I instantiated MySealedClass earlier in the code without using the using statement as follows:
MySealedClass msc = new MySealedClass()
The code can get past this point and I can then call methods on it.
I've seen some examples on MSDN where the using statement code is translated into a try catch pattern by the compiler, but I don't think this explains the error as the error happens before my main block code.
Can anyone explain if the using statement is doing something extra? e.g. is it scanning the rest of the code block and if there is something it doesn't like, then calling the Dispose() method.
My suspicion lies with IIS, Before, I had unsafe code errors (despite the right configuration in web.config) but I had forgotten to get IIS to run the app as x64. After doing that using regedit it was fine.
Additional info: In the using block, there is unsafe code and calls to external dlls using the [DllImport] attribute.
Many thanks
Upvotes: 2
Views: 183
Reputation: 883
Accoring to MSDN Documentation, "The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object."
Why don't you debug the unsafe code you mentioned within the using block. May be the exception thrown within the external dll is causing a call to Displose() method?
Upvotes: 0
Reputation: 60694
using (MySealedClass msc = new MySealedClass())
{
//Code doesn't reach here. Dispose() is called beforehand
//My code here . . .
}
is translated by the compiler to something quite similar to this:
MySealedClass msc = null;
try
{
msc = new MySealedClass();
//My code here . . .
}finally{
if(msc != null){
((IDisposable)msc).Dispose():
}
}
The compiler does not check your code beforehand and skips it if it sees something it does not like.
So to me it seems like before you get to the point you are checking you get an exception that causes it to go to the finally block and dispose your object.
Upvotes: 2