参考是否可能是GC'd当前被"使用"块消耗的?

hal*_*ton 1 .net c# garbage-collection

鉴于,

using (var abc = new Abc())
{

    // abc is not used here at all.

 }
Run Code Online (Sandbox Code Playgroud)

abc是否有可能在结束大括号之前收集垃圾?

Cod*_*ike 5

没有.在内部,有一个引用,abc直到结束大括号.

生成的IL代码如下所示:

  IL_0001:  newobj     instance void ConsoleApplication1.Abc::.ctor()
  IL_0006:  stloc.0
  .try
  {
    IL_0007:  nop
    IL_0008:  nop
    IL_0009:  leave.s    IL_001b
  }  // end .try
  finally
  {
    IL_000b:  ldloc.0
    IL_000c:  ldnull
    IL_000d:  ceq
    IL_000f:  stloc.1
    IL_0010:  ldloc.1
    IL_0011:  brtrue.s   IL_001a
    IL_0013:  ldloc.0
    IL_0014:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
    IL_0019:  nop
    IL_001a:  endfinally
  }  // end handler
Run Code Online (Sandbox Code Playgroud)

using语句转换为IL代码时,编译器实际上将其转换为完整try / finally块,并.Dispose()在您的实例上调用该方法Abc.所以基本上把它变成了这样的东西:

Abc abc = new Abc();
try
{
}
finally
{
    abc.Dispose();
}
Run Code Online (Sandbox Code Playgroud)