MSDN here上的页面从来没有真正明确指出Dispose方法不是线程安全的,但对我的阅读而言,它们的代码暗示着不,它们不是线程安全的,如果需要,您需要说明。
具体地,在该示例代码中的注释:
// This class shows how to use a disposable resource.
// The resource is first initialized and passed to
// the constructor, but it could also be
// initialized in the constructor.
// The lifetime of the resource does not
// exceed the lifetime of this instance.
// This type does not need a finalizer because it does not
// directly create a native resource like a file handle
// or memory in the unmanaged heap.
public class DisposableResource : IDisposable
{
private Stream _resource;
private bool _disposed;
// The stream passed to the constructor
// must be readable and not null.
public DisposableResource(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("Stream in null.");
if (!stream.CanRead)
throw new ArgumentException("Stream must be readable.");
_resource = stream;
_disposed = false;
}
// Demonstrates using the resource.
// It must not be already disposed.
public void DoSomethingWithResource() {
if (_disposed)
throw new ObjectDisposedException("Resource was disposed.");
// Show the number of bytes.
int numBytes = (int) _resource.Length;
Console.WriteLine("Number of bytes: {0}", numBytes.ToString());
}
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;
}
}
}
也许这可以帮助:http://stackoverflow.com/questions/151000/finalizers-and-dispose。 – 2011-02-17 04:05:39
谢谢,但那不是我所问的。此外,我并不在乎这里的终结者。 – Noldorin 2011-02-17 04:07:01
重新说明你的观点,你不应该明确调用`Dispose`并且不要依赖Finalizer线程来做到这一点吗? – 2011-02-17 04:07:39