@Jon Skeet有answered the問題非常好,但讓我湊錢與評論,我覺得應該是自己的一個答案。
這是很常見的使用using
代碼塊暫時獲得一些資源,或進入某種形式的作用域的代碼,你想從一個乾淨的退出。我一直這樣做,特別是在我的業務邏輯控制器中,我有一個系統推遲更改事件,直到執行代碼塊,避免多次副作用,或者在我爲他們做好準備之前,等
爲了使代碼看起來更明顯的使用它的程序員,你應該看看使用一個臨時值,你use
而不是有資源的對象,並從一個方法名返回它告訴程序員它正在做什麼,即。暫時獲取一些資源。
讓我來舉個例子。
取而代之的是:
using (node) { ... }
你這樣做:
using (node.ResourceScope()) { ... }
因此,你實際上並不處置的任何一次以上,因爲ResourceScope
將返回處置的新值,並且底層節點將保持原樣。
下面是一個例子實現(未經證實,從內存中輸入):
public class Node
{
private Resource _Resource;
public void AcquireResource()
{
if (_Resource == null)
_Resource = InternalAcquireResource();
}
public void ReleaseResource()
{
if (_Resource != null)
{
InternalReleaseResource();
_Resource = null;
}
}
public ResourceScopeValue ResourceScope()
{
if (_Resource == null)
return new ResourceScopeValue(this);
else
return new ResourceScopeValue(null);
}
public struct ResourceScopeValue : IDisposable
{
private Node _Node;
internal ResourceScopeValue(Node node)
{
_Node = node;
if (node != null)
node.AcquireResource();
}
public void Dispose()
{
Node node = _Node;
_Node = null;
if (node != null)
node.ReleaseResource();
}
}
}
這可以讓你做到這一點:
Node node = ...
using (node.ResourceScope()) // first call, acquire resource
{
CallSomeMethod(node);
} // and release it here
...
private void CallSomeMethod(Node node)
{
using (node.ResourceScope()) // due to the code, resources will not be 2x acquired
{
} // nor released here
}
,我返回一個結構,而不是事實IDisposable
意味着你不會得到拳擊開銷,相反公開的.Dispose方法只會在using
-block退出時被調用。
在此主題深入討論:http://stackoverflow.com/questions/2101524/is-it-abusive-to-use-idisposable-and-using-as-a-means-for-getting-scoped- behav – 2010-02-23 11:58:27
@nobugz - 我不認爲這是完全相同的事情 - 儘管那個線程肯定是相關的 – philsquared 2010-02-23 12:16:56