@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