-
Let's say I have some code like this: try
{
using var bla = Foo(some_byte_array);
// some stuff here
}
catch () { }
class Foo : IDisposable
{
IntPtr AllocationHandle;
public Foo(byte[] buffer)
{
//do some allocation with AllocationHandle here
throw new Exception();
}
public void Dispose()
{
//free AllocationHandle here
}
} Is .NET runtime calling |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
No, Dispose is not called in this situation. If you can't ensure that Dispose is called under any and every circumstances (which is often the case), look into using SafeHandle instead of IntPtr/nint. If you can't use SafeHandles for some reason and stick with IntPtr/nint, then implement a finalizer and the Dispose pattern (Visual Studio can generate the skeleton of this Dispose pattern) Note that your {
Foo bla = new Foo(some_byte_array);
try
{
// some stuff here
}
finally
{
((IDisposable) bla)?.Dispose();
}
} (see also the C# language spec: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#1314-the-using-statement) When |
Beta Was this translation helpful? Give feedback.
I don't understand. TheScratch that. I misread your comment and didn't notice you used "this" only as an anchor for a link to an article about finalizers...this
keyword is unrelated. How/why do you think that thethis
keyword might matter here?Yes. The finalizer is guaranteed to be run (once the GC comes around to collect and process the finalization queue).
Because, for the ctor to be executed, the instance itself has to already exist (otherwise you wouldn't be able to access instance members or use the
this
keyword in ctors). Once an instance of a type with a finalizer exists and cannot be accessed by any possible continuation of execution (other than the running of finalizers thems…