Last active
July 20, 2019 09:02
-
-
Save tommasobertoni/14a20c684c897c6f06f4bbc76d5da064 to your computer and use it in GitHub Desktop.
AsyncCollector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace Utils | |
{ | |
class AsyncCollector | |
{ | |
public IReadOnlyList<Task> Tasks => _tasks.AsReadOnly(); | |
private readonly List<Task> _tasks = new List<Task>(); | |
public void Register(Func<Task> asyncDelegate) => | |
this.Register(asyncDelegate, out _); | |
public void Register(Func<Task> asyncDelegate, out Task registeredTask) | |
{ | |
registeredTask = asyncDelegate(); | |
_tasks.Add(registeredTask); | |
} | |
#region Overloads that don't require closures | |
public void Register<TSubject>(TSubject subject, Func<TSubject, Task> asyncDelegate) => | |
this.Register(subject, asyncDelegate, out _); | |
public void Register<TSubject>(TSubject subject, Func<TSubject, Task> asyncDelegate, out Task registeredTask) | |
{ | |
registeredTask = asyncDelegate(subject); | |
_tasks.Add(registeredTask); | |
} | |
#endregion | |
public async Task WhenAll(bool clearAfterwards = true) | |
{ | |
try | |
{ | |
await Task.WhenAll(_tasks); | |
} | |
finally | |
{ | |
if (clearAfterwards) | |
_tasks.Clear(); | |
} | |
} | |
public void Clear() => _tasks.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment