该处置实现IDisposable成员 [英] Disposing the members that implement IDisposable
问题描述
在我的Dispose方法(如下面的那个),每次我想打电话给someObj.Dispose()我也有someObj中!= NULL检查。
In my Dispose methods (like the one below), everytime i want to call someObj.Dispose() i also have a check for someObj!=null.
那是因为我的一部分不好的设计?
是其确定所有成员(实现IDisposable接口)中的对象正在使用的处置被称为无需NullReference异常的风险更清洁的方式?
Is that because of bad design on my part? Is their a cleaner way to ascertain that Dispose of all the members (implementing IDisposable) being used in an object is called without having a risk of NullReference exception ?
protected void Dispose(bool disposing)
{
if (disposing)
{
if (_splitTradePopupManager != null)
{
_splitTradePopupManager.Dispose();
}
}
}
感谢您的关注。
Thanks for your interest.
推荐答案
也许别人可以附和这一点,但我不个人认为这是一个设计缺陷 - 只有最安全的方式做到这一点。
Maybe someone else can chime in on this, but I don't personally think it's a design flaw -- just the safest way to do it.
这是说,没有什么阻止你从包装你的空
检查和处置
呼叫的简便方法:
That said, nothing's stopping you from wrapping your null
check and Dispose
call in a convenient method:
private void DisposeMember(IDisposable member)
{
if (member != null)
member.Dispose();
}
那么你的的Dispose
方法可能看起来有点清洁:
Then your Dispose
method could look a bit cleaner:
protected void Dispose(bool disposing)
{
if (disposing)
{
DisposeMember(_splitTradePopupManager);
DisposeMember(_disposableMember2);
DisposeMember(_disposableMember3);
}
}
作为额外的奖励,这也解决了潜在的竞争条件在原来的代码。如果在多线程上下文中运行,在如果(_field!= NULL)_field.Dispose()
可导致的NullReferenceException $ C $格局C>在
_field
是检查和处置(罕见,但有可能)之间设置为空
。通过 _field
作为参数的方法,如 DisposeMember
复制参考方法的局部变量,消除这种可能,不太可能,因为它是。
As an added bonus, this also resolves a potential race condition in your original code. If running in a multithreaded context, the if (_field != null) _field.Dispose()
pattern can result in a NullReferenceException
when _field
is set to null
between the check and the disposal (rare, but possible). Passing _field
as an argument to a method such as DisposeMember
copies the reference to a local variable in the method, eliminating this possibility, unlikely as it is.
这篇关于该处置实现IDisposable成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!