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 . |
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.
![]() |
---|
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. |
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); }