TaskBlocksUsingTResource, TResult Method (FuncTaskTResource, FuncTaskTResource, TaskTResult) |
Namespace: Rackspace.Threading
public static Task<TResult> Using<TResource, TResult>( Func<Task<TResource>> resource, Func<Task<TResource>, Task<TResult>> 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)) { return 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, prior to returning the result of the body.
public Task<string> UsingWithResult() { return TaskBlocks.Using( () => AcquireResourceAsync(), task => task.Result.ReadToEndAsync()); } private Task<StringReader> AcquireResourceAsync() { // this would generally contain an asynchronous call return CompletedTask.FromResult(new StringReader("Text to read")); }
For reference, the following example demonstrates a (nearly) equivalent implementation of this behavior using the / operators.
public async Task<string> UsingWithResultAsyncAwait() { using (StringReader resource = await AcquireResourceAsyncAwait()) { return await resource.ReadToEndAsync(); } } private async Task<StringReader> AcquireResourceAsyncAwait() { // this would generally contain an asynchronous call return new StringReader("Text to read"); }