Geeks With Blogs
Josh Reuben

I’m leveraging a ConcurrentPriorityQueue – from


This class basically is a thread safe IProducerConsumerCollection wrapper for a binary heap that prioritizes smaller values. You use it as you would a dictionary, where the priority is the key, except you can have duplicate keys (ie values with the same priority).

I needed to demonstrate to a customer that it worked.

I set up my queue and my priority enum values:

var q = new ConcurrentPriorityQueue<int, string>();

var priorityValues = Enum.GetValues(typeof(JobPriority));

I then randomly enqueued different priorities from different threads:

var random = new Random();
Parallel.For(0, 1000, i =>
    var randomPriority = (JobPriority) priorityValues.GetValue(random.Next(priorityValues.Length));
    Debug.WriteLine("enqueueing:" + randomPriority);
    q.Enqueue((int) randomPriority, randomPriority.ToString());
and finally I asserted that dequeueing occurs in order:
while (q.TryDequeue(out printJobKVP))
    var jobPriority = (JobPriority)Enum.Parse(typeof(JobPriority), printJobKVP.Value);
    Assert.IsTrue(jobPriority >= previousJobPriority);
    previousJobPriority = jobPriority;

Posted on Sunday, December 4, 2011 1:05 PM Parallelism | Back to top

Comments on this post: Unit Testing a ConcurrentPriorityQueue

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © JoshReuben | Powered by: | Join free