IDisposable Interface
IDisposable is a accepted programme in the .NET framework. It is implemented by classes that stop managed resources or instances of added types that also compel IDisposable. The programme includes a azygos method, Dispose, which crapper be titled to direct promulgation the unmanaged resources and liberated up module or grouping resources accordingly. When implemented correctly, useable classes also enable the substance holder to liberated up those resources, preventing leaks.
If you are nonindustrial multi-threaded cipher or are using parallelism, the feat of IDisposable should be thread-safe. In this article we module wager how this crapper be achieved.
Thread-Safe IDisposable
To begin, we’ll countenance at whatever cipher that shows a accepted feat of IDisposable but that is not thread-safe. I won’t exposit the implementation. If you are would aforementioned more aggregation most the base pattern, feature the “Implementing IDisposable” article. The cipher beneath shows the distribution class. It does not stop some unmanaged resources direct so no finalizer has been included. It does stop a meaning to a Stream object, which is willing of aright in the fortified Dispose method.
public collection DisposableResource : IDisposable
{
bool _disposed;
Stream _stream;
open DisposableResource()
{
_stream = File.OpenRead(@"c:\test\test.txt");
}
open daylong FileLength()
{
if (_disposed) intercommunicate newborn ObjectDisposedException(typeof(DisposableResource).FullName);
convey _stream.Length;
}
fortified realistic vacuum Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_stream != null) _stream.Dispose();
}
_stream = null;
_disposed = true;
}
}
open vacuum Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Adding Thread-Safety
The above feat presents individual problems when accessed by individual clothing concurrently. Each is a fault that would exclusive be seen intermittently and could be arduous to find. The problems include:
- It is doable for digit clothing to admittance the unmanaged inventiveness at the aforementioned time. If the inventiveness is not thread-safe this could provide unheralded results.
- It is doable for digit arrange to move disposing resources whilst added uses them. This would hap if both clothing passed the analyse that _disposed is false, before digit willing of the inventiveness and the added proven to ingest it. Using a willing goal or free inventiveness could drive an omission or unheralded lateral effects.
- Two clothing could endeavor to promulgation the resources at the aforementioned time. In the warning cipher this could advance to an ObjectDisposedException.
Tags: Programming