簡體   English   中英

使用塊計數作為它捕獲的IDisposable的引用嗎?

[英]Does a using block count as a reference to the IDisposable it captures?

假設我已經定義了以下方法。

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

是。

你不能在沒有參考的情況下處置某些東西。

規范聲明 using (expression) { statement }編譯為:

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

resource是一個參考。

在作用域末尾沒有對局部變量的隱式引用。 在上次實際引用對象之后,實現可能(但不是必需)進行垃圾收集。 換句話說,你的第二個代碼塊是不正確的 ,因為x 允許該塊結束之前被收集。

{
    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

using塊創建一個局部變量,以便在using塊的末尾調用Dispose 即使您沒有明確命名變量,引用也將一直存在,直到塊結束。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM