3

假设我已经定义了以下方法。

static object F()
{
    return new object();
}

如果我编写如下代码,则object在范围结束之前不能对返回的内容进行垃圾收集。

{
    object x = F();
    // cannot yet garbage collect the object
    // returned by F (referenced as variable x)
}
// can now garbage collect the object
// returned by F (referenced as variable x)

如果我编写如下代码,返回object后可以立即进行垃圾回收F

{
    F();
    // can now garbage collect the object
    // returned by F
}

但是现在假设我将定义更改为F以下内容。

static IDisposable F()
{
    return new SomeDisposableObject();
}

如果我编写如下代码,返回的对象不能被垃圾收集,直到using块结束才会被释放。

using (IDisposable x = F())
{
} // immediately x.Dispose()
// can now garbage collect the object
// returned by F

如果我编写如下代码,行为是什么?对 C# 语言规范的引用是一个加号。

using (F())
{
}

块是否using算作对返回的实例的引用F

4

2 回答 2

6

是的。

你不能在没有引用的情况下处置某些东西。

该规范指出编译using (expression) { statement }为:

{
   ResourceType resource = expression;
   try {
      statement;
   }
   finally {
      if (resource != null) ((IDisposable)resource).Dispose();
   }
}

resource是参考。

于 2013-07-26T16:46:33.750 回答
1

There is no implicit reference to a local variable at the end of a scope. An implementation may, but is not required to, garbage collect an object after your last actual reference to it. In other words, your second code block is not correct, because x is allowed to be collected before the end of the block.

{
    object x = F();
    // <-- x IS ALLOWED to be collected here
    Thread.Sleep(5000);
    // <-- The object x ref'd IS ALLOWED to be collected here, if it wasn't earlier
}
// <-- The object x ref'd IS ALLOWED to be collected here, if it wasn't earlier

A using block creates a local variable in order to call Dispose at the end of the using block. Even if you do not explicitly name the variable, the reference will be alive until the end of the block.

using (F())
{
    // The instance returned by F IS NOT allowed to be collected here
    Thread.Sleep(5000);
    // The instance returned by F IS NOT allowed to be collected here
}
// The instance returned by F IS allowed to be collected here
于 2013-07-26T17:37:47.287 回答