using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
namespace ComposableAsync
{
///
/// implementation aggregating other
///
public sealed class ComposableAsyncDisposable : IAsyncDisposable
{
private readonly ConcurrentQueue _Disposables;
///
/// Build an empty ComposableAsyncDisposable
///
public ComposableAsyncDisposable()
{
_Disposables = new ConcurrentQueue();
}
///
/// Add an to the ComposableAsyncDisposable
/// and returns it
///
///
///
///
public T Add(T disposable) where T: IAsyncDisposable
{
if (disposable == null)
return default(T);
_Disposables.Enqueue(disposable);
return disposable;
}
///
/// Dispose all the resources asynchronously
///
///
public Task DisposeAsync()
{
var tasks = _Disposables.ToArray().Select(disposable => disposable.DisposeAsync()).ToArray();
return Task.WhenAll(tasks);
}
}
}