Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Last active April 26, 2016 15:26
Show Gist options
  • Select an option

  • Save valerysntx/a3623da217012cd108a0 to your computer and use it in GitHub Desktop.

Select an option

Save valerysntx/a3623da217012cd108a0 to your computer and use it in GitHub Desktop.
Async producer-consumer queue
async Task Main()
{
using (var q = new CommandsPipeline(2))
{
await Task.Run(()=> {
var queue = q;
Parallel.ForEach(string.Format("StringParallelQuery"),
new ParallelOptions {
MaxDegreeOfParallelism = 1
},
async (letter) => {
await queue.EnqueueTask (() => letter.Dump());
});
}).ConfigureAwait(true);
}
}
public class CommandsPipeline : IDisposable
{
BlockingCollection<Action> commandQueue = new BlockingCollection<Action>();
public CommandsPipeline (int parallelDegree)
{
// Create and start a separate Task for each consumer:
for (int i = 0; i < parallelDegree; i++){
Task.Factory.StartNew (Consume);
}
}
public void Dispose() { commandQueue.CompleteAdding(); }
public Task EnqueueTask (Action action) {
commandQueue.Add (action);
return Task.FromResult(action );
}
void Consume()
{
// This sequence that we’re enumerating will block when no elements
// are available and will end when CompleteAdding is called.
foreach (Action action in commandQueue.GetConsumingEnumerable()){
action(); // Perform task.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment