/// <summary> /// Create disposable /// </summary> /// <param name="disposable"></param> /// <param name="disposeAsync"></param> public AsyncDisposable(IDisposable disposable = null, Func <Task> disposeAsync = null) { _disposable = disposable; if (disposeAsync != null) { _disposeAsync = () => Try.Async(() => disposeAsync.Invoke()); } else { _disposeAsync = () => Task.CompletedTask; } }
/// <summary> /// Safe waiting for disposables /// </summary> /// <param name="tasks"></param> /// <returns></returns> #pragma warning disable IDE1006 // Naming Styles public static async Task <IAsyncDisposable[]> WhenAll( IEnumerable <Task <IAsyncDisposable> > tasks) { #pragma warning restore IDE1006 // Naming Styles try { return(await Task.WhenAll(tasks)); } catch { foreach (var task in tasks) { if (task.IsCompleted) { await Try.Async(() => task.Result.DisposeAsync().AsTask()); } } throw; } }
/// <summary> /// Safe waiting for disposables /// </summary> /// <param name="disposables"></param> /// <returns></returns> public static Task DisposeAsync(IEnumerable <IAsyncDisposable> disposables) { return(Try.Async(() => Task.WhenAll(disposables .Where(d => d != null) .Select(d => d.DisposeAsync().AsTask())))); }