ScopeGuardT Class |
Namespace: Lawo
public sealed class ScopeGuard<T> : IDisposable where T : IDisposable
The ScopeGuardT type exposes the following members.
Name | Description | |
---|---|---|
Resource | Gets the resource object passed to CreateT(T). |
Name | Description | |
---|---|---|
Dismiss | Dismisses the scope guard. Subsequent calls to Dispose will have no effect. | |
Dispose | ||
Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.) | |
GetHashCode | Serves as the default hash function. (Inherited from Object.) | |
GetType | Gets the Type of the current instance. (Inherited from Object.) | |
ToString | Returns a string that represents the current object. (Inherited from Object.) |
Often, a function needs to do other stuff besides constructing the resource object (e.g. creating child resource objects that the main resource will own or setting some properties after creation). In .NET pretty much any of these operations can fail by throwing an exception. Without the help of this class, one try-catch block would be necessary for the creation of each of these resource objects. In the try block the resource is created and possibly initialized, in the catch block the resource is disposed and the exception rethrown.
This class is an adapted version of the facility presented in this article.
StreamWriter CreateWriter() { using (ScopeGuard<FileStream> streamGuard = ScopeGuard.Create(new FileStream("C:\test.txt", FileMode.CreateNew))) using (ScopeGuard<StreamWriter> writerGuard = // At this point, the FileStream object is automatically disposed if the StreamWriter constructor throws ScopeGuard.Create(new StreamWriter(streamGuard.Resource))) { // Here both resource objects are automatically disposed if the following statement throws writerGuard.Resource.AutoFlush = true; writerGuard.Dismiss(); // The whole creation succeeded -> dismiss both guards streamGuard.Dismiss(); return writerGuard.Resource; } }