Unit Testing a ConcurrentPriorityQueue

I’m leveraging a ConcurrentPriorityQueue – from http://code.msdn.microsoft.com/ParExtSamples.

clip_image002

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;
}
 

Print | posted on Sunday, December 4, 2011 1:05 PM

Feedback

No comments posted yet.

Your comment:





 
 

Copyright © JoshReuben

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski