Last active
April 26, 2016 15:26
-
-
Save valerysntx/a3623da217012cd108a0 to your computer and use it in GitHub Desktop.
Async producer-consumer queue
This file contains hidden or 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
| 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