Skip to content

Instantly share code, notes, and snippets.

@mnadel
Last active May 25, 2020 17:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnadel/df2ec09fe7eae9ba8938 to your computer and use it in GitHub Desktop.
Save mnadel/df2ec09fe7eae9ba8938 to your computer and use it in GitHub Desktop.
Applying Backpressure (aka Throttling) in TPL Dataflow
using System.Threading;
using System.Threading.Tasks.Dataflow;
class Pipeline<T>
{
private readonly SemaphoreSlim _semaphore;
private readonly BufferBlock<T> _buffer;
Pipeline(Action<T> action, int capacity)
{
_semaphore = new SemaphoreSlim(capacity, capacity);
_buffer = new BufferBlock<T>();
var actionBlock = new ActionBlock<T>(t => {
try
{
action(t);
}
finally
{
_semaphore.Release();
}
});
_buffer.LinkTo(actionBlock);
}
void Post(T message)
{
_semaphore.Wait();
_buffer.Post(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment