Last active
May 25, 2020 17:47
-
-
Save mnadel/df2ec09fe7eae9ba8938 to your computer and use it in GitHub Desktop.
Applying Backpressure (aka Throttling) in TPL Dataflow
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.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