/// <summary> /// Convenience method to asynchronously get <see cref="AsyncResourceUsage{TResource}"/> from this <see cref="AsyncResourcePool{TResource}"/> by first calling <see cref="AsyncResourcePool{TResource}.GetResourceUsage"/> and then <see cref="AsyncResourceUsage{TResource}.AwaitForResource"/>. /// </summary> /// <typeparam name="TResource">The type of resources handled by this pool.</typeparam> /// <param name="pool">This <see cref="AsyncResourcePool{TResource}"/>.</param> /// <param name="token">The <see cref="CancellationToken"/> to bind returned <see cref="AsyncResourceUsage{TResource}"/> to.</param> /// <returns>Asynchronously returns <see cref="AsyncResourceUsage{TResource}"/> which has its <see cref="AsyncResourceUsage{TResource}.Resource"/> property ready to use without further awaiting.</returns> /// <exception cref="NullReferenceException">If this <see cref="AsyncResourcePool{TResource}"/> is <c>null</c>.</exception> public static async Task <AsyncResourceUsage <TResource> > GetResourceUsageAsync <TResource>(this AsyncResourcePool <TResource> pool, CancellationToken token) { var retVal = pool.GetResourceUsage(token); await retVal.AwaitForResource(); return(retVal); }
/// <summary> /// Takes an existing resource or creates a new one, runs the given asynchronous callback for it, and returns it back into the pool. /// </summary> /// <param name="pool">This <see cref="AsyncResourcePool{TResource}"/>.</param> /// <param name="user">The asynchronous callback to use the resource.</param> /// <param name="token">The optional <see cref="CancellationToken"/> to use during asynchronous operations inside <paramref name="user"/> callback.</param> /// <returns>A task which completes when <paramref name="user"/> callback completes and resource is returned back to the pool.</returns> /// <exception cref="NullReferenceException">If this <see cref="AsyncResourcePool{TResource}"/> is <c>null</c>.</exception> public static async Task UseResourceAsync <TResource>(this AsyncResourcePool <TResource> pool, Func <TResource, Task> user, CancellationToken token) { var usage = pool.GetResourceUsage(token); try { await usage.AwaitForResource(); await user(usage.Resource); } finally { await usage.DisposeAsync(); } }