Sampy wrote:
I believe the C++ did some work to make code they generate more C++-y so these rules may work in that language. That's hearsay though.
That's partially correct. If you use the deterministic finalization pattern in an arbitrary scope, it generates a try block to make sure the Dispose method is called at the end of the scope (similar to a using statement in C# or VB). However, just like in C#
or VB the object can't actually be collected until the method ends.
For instance:
int main()
{
Console::WriteLine(L"Before");
{
System::IO::StreamWriter writer(L"D:\test.txt");
writer.WriteLine(L"Hello");
}
Console::WriteLine(L"After");
return 0;
}
This is compiled to the following IL when using /clr:safe:
.method assembly static int32 main() cil managed
{
.entrypoint
// Code size 65 (0x41)
.maxstack 2
.locals init ([0] class [mscorlib]System.IO.StreamWriter writer,
[1] int32 V_1,
[2] class [mscorlib]System.IO.StreamWriter modopt([mscorlib]System.Runtime.CompilerServices.IsConst) V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.1
IL_0002: ldstr "Before"
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: ldstr "D:\test.txt"
IL_0011: newobj instance void [mscorlib]System.IO.StreamWriter::.ctor(string)
IL_0016: stloc.2
.try
{
IL_0017: ldloc.2
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: ldstr "Hello"
IL_001f: callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string)
IL_0024: leave.s IL_002d
} // end .try
fault
{
IL_0026: ldloc.0
IL_0027: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_002c: endfinally
} // end handler
IL_002d: ldloc.0
IL_002e: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0033: ldstr "After"
IL_0038: call void [mscorlib]System.Console::WriteLine(string)
IL_003d: ldc.i4.0
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ret
} // end of method 'Global Functions'::main
What confuses me though is why they don't use try/finally, but instead put a call to Dispose in a fault clause and again in the normal flow of execution.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.