For something this simple, a SemaphoreSlim
should suffice. TPL Dataflow is great, especially if you're looking to limit work in one part of a larger pipeline. However, in your scenario it sounds more like you really do just have one action that you need to throttle.
Doing it asynchronously is quite simple:
var semaphore = new SemaphoreSlim(50);
var tasks = list.Cast<CloudBlob>().Select(async x =>
{
using (await semaphore.TakeAsync())
await x.DeleteAsync();
});
await Task.WhenAll(tasks);
where TakeAsync
is defined as:
private sealed class SemaphoreSlimKey : IDisposable
{
private readonly SemaphoreSlim _semaphore;
public SemaphoreSlimKey(SemaphoreSlim semaphore) { _semaphore = semaphore; }
void IDisposable.Dispose() { _semaphore.Release(); }
}
public static async Task<IDisposable> TakeAsync(this SemaphoreSlim semaphore)
{
await semaphore.WaitAsync().ConfigureAwait(false);
return new SemaphoreSlimKey(semaphore);
}