如果您不確定對象是否已處置,您應該調用Dispose
方法本身,而不是像Close
這樣的方法。儘管框架並不能保證Dispose方法必須在沒有異常的情況下運行,即使對象之前已經被拋棄了,它也是一個常見的模式,並且據我所知,在框架中的所有可丟棄對象上都有實現。
爲Dispose
典型模式,按照Microsoft:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (_resource != null)
_resource.Dispose();
Console.WriteLine("Object disposed.");
}
// Indicate that the instance has been disposed.
_resource = null;
_disposed = true;
}
}
通知上_disposed
檢查。如果您要調用實現此模式的Dispose
方法,則可以根據需要多次調用Dispose而不觸發異常。
http:// stackoverflow。com/questions/192206/how-do-one-tell-if-an-idisposable-object-reference-is-dispos – w69rdy 2010-08-11 10:55:56
我知道這個問題一般來說太常見了,因爲沒有在stackoverflow上進行問答,但我沒有搜索到它。 – jethro 2010-08-11 12:01:02