Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Common.Utilities
- {
- /*
- //example:
- //countdown event to determine when the last worker is completed
- CountdownEvent countdown = new CountdownEvent(4);
- using (var queue = new BlockingQueue(4))
- {
- for (int i = 0; i < actionsCount; i++)
- {
- int id = i;
- queue.EnqueueTask(() =>
- {
- Thread.Sleep(1000);
- return "Worker# " + id + " Finished";
- }).ContinueWith(tsk =>
- {
- if(!countdown.Signal())
- Console.WriteLine(tsk.Result);
- else
- Console.WriteLine("All completed");
- });
- }
- }
- */
- public class BlockingQueue : IDisposable
- {
- readonly BlockingCollection<WorkItem> _taskQueue = new BlockingCollection<WorkItem>();
- public BlockingQueue(int workerCount)
- {
- // Create and start a separate Task for each consumer:
- for (int i = 0; i < workerCount; i++)
- Task.Factory.StartNew(Consume);
- }
- public void Dispose()
- {
- _taskQueue.CompleteAdding();
- }
- public Task<object> EnqueueTask(Func<object> action, CancellationToken? cancelToken = null)
- {
- var tcs = new TaskCompletionSource<object>();
- _taskQueue.Add(new WorkItem(tcs, action, cancelToken));
- return tcs.Task;
- }
- void Consume()
- {
- foreach (WorkItem workItem in _taskQueue.GetConsumingEnumerable())
- {
- if (workItem.CancelToken.HasValue &&
- workItem.CancelToken.Value.IsCancellationRequested)
- {
- workItem.TaskSource.SetCanceled();
- }
- else
- {
- try
- {
- //call worker's action and set task source's result
- object result = workItem.Action();
- workItem.TaskSource.SetResult(result);
- }
- catch (OperationCanceledException ex)
- {
- if (ex.CancellationToken == workItem.CancelToken)
- workItem.TaskSource.SetCanceled();
- else
- workItem.TaskSource.SetException(ex);
- }
- catch (Exception ex)
- {
- workItem.TaskSource.SetException(ex);
- }
- }
- }
- }
- class WorkItem
- {
- public readonly TaskCompletionSource<object> TaskSource;
- public readonly Func<object> Action;
- public readonly CancellationToken? CancelToken;
- public WorkItem(TaskCompletionSource<object> taskSource, Func<object> action, CancellationToken? cancelToken)
- {
- TaskSource = taskSource;
- Action = action;
- CancelToken = cancelToken;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment