Priority queue implementation using BlockingCollection
Problem statement:
- There are multiple queue Queue 1, Queue 2, Queue 3..... etc.
- Queue 1 have higher priority than Queue 2 and Queue 2 have higher priority than queue 3 same pattern will be followed for other queues.
- Elements can be pass to the queue at any point time.
- Element priority will be depend on queue periority & elements inside the current queue.
Sample Problem:
- Queue 1 contains odd numbers.
- Queue 2 contains even numbers.
- Odd numbers should get priority over even numbers.
Code Snippet:
public class PriorityQueue { private BlockingCollection<ItemData>[] PeriorityQueueList; private CancellationTokenSource cancelTokenSource = new CancellationTokenSource(); BlockingCollection<ItemData> Queue1 = new BlockingCollection<ItemData>(); BlockingCollection<ItemData> Queue2 = new BlockingCollection<ItemData>(); public PeriorityQueue() { PeriorityQueueList = new[] { Queue1, Queue2 }; Task.Factory.StartNew(() => FillQueue()); Task.Factory.StartNew(() => StartProcessQueue()); Console.ReadKey(); } private void StartProcessQueue() { while (cancelTokenSource != null && !cancelTokenSource.IsCancellationRequested) { try { ItemData data; BlockingCollection<ItemData>.TakeFromAny(PeriorityQueueList, out data, cancelTokenSource.Token); Console.WriteLine("Number out from queue: " + data.Item); } catch (Exception) { Console.WriteLine("No Data in Queue"); } } } private void FillQueue() { Queue1.Add(new ItemData() { Item = "" }); for (int num = 1; num <= 10; num++) { if (num % 2 == 1) { Queue1.Add(new ItemData() { Item = num }); Console.WriteLine("Number added to Queue1 :"+num); } else { Queue2.Add(new ItemData() { Item = num }); Console.WriteLine("Number added to Queue2 :" + num); } } } } public class ItemData { public object Item { get; set; } }
Output:
Number added to Queue1 :1
Number added to Queue2 :2
Number added to Queue1 :3
Number added to Queue2 :4
Number added to Queue1 :5
Number added to Queue2 :6
Number added to Queue1 :7
Number added to Queue2 :8
Number added to Queue1 :9
Number added to Queue2 :10
Number out from queue: 1
Number out from queue: 3
Number out from queue: 5
Number out from queue: 7
Number out from queue: 9
Number out from queue: 2
Number out from queue: 4
Number out from queue: 6
Number out from queue: 8
Number out from queue: 10
As in above example event elements are added to Queue 2 & odd elements in Queue 1.
On processing the queue elements. Priority queue will give preference to odd elements & then even elements.
0 comments :
Post a Comment