TaskBlocksUsingTResource Method (FuncTaskTResource, FuncTaskTResource, Task) |
Namespace: Rackspace.Threading
public static Task Using<TResource>( Func<Task<TResource>> resource, Func<Task<TResource>, Task> body ) where TResource : IDisposable
Exception | Condition |
---|---|
ArgumentNullException |
If resource is . -or- If body is . |
InvalidOperationException |
If resource returns . |
This code implements support for the following construct without requiring the use of /.
using (IDisposable disposable = await resource().ConfigureAwait(false)) { await body(disposable).ConfigureAwait(false); }
This method expands on the using statement provided by C# by implementing support for IAsyncDisposable as described in IAsyncDisposable, using statements, and async/await.
Notes to Callers |
---|
If the resource function throws an exception, or if it returns , or if the TaskTResult it returns does not complete successfully, the resource will not be acquired by this method. In either of these situations the caller is responsible for ensuring the resource function cleans up any resources it creates. |
The following example asynchronously acquires a resource by calling the user method AcquireResourceAsync. The resource will be disposed after the body executes. No result is return from this operation, as the body of the task block represents an asynchronous operation that does not return a result.
public Task Using(StringBuilder builder) { return TaskBlocks.Using( () => AcquireResourceAsync(builder), task => task.Result.WriteAsync(SampleText)); } private Task<StringWriter> AcquireResourceAsync(StringBuilder builder) { // this would generally contain an asynchronous call return CompletedTask.FromResult(new StringWriter(builder)); }
For reference, the following example demonstrates a (nearly) equivalent implementation of this behavior using the / operators.
public async Task UsingAsyncAwait(StringBuilder builder) { using (StringWriter resource = await AcquireResourceAsyncAwait(builder)) { await resource.WriteAsync(SampleText); } } private async Task<StringWriter> AcquireResourceAsyncAwait(StringBuilder builder) { // this would generally contain an asynchronous call return new StringWriter(builder); }