Can you show a short but complete program which illustrates your
problem?
Here she be. I would also appreciate it if you could confirm that I'm
doing the locking correctly. I need the AddItem function to run in one
thread and GetPriorityItem function to run in a different thread. It
seems that running outside the debugger is significantly faster at
exceptions, but still way slower than otherwise. I'm still entirely
astounded at how drastic the difference is between the two.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace QueueDemoApp
{
class Program
{
class LeveledQueue
{
Queue[] queues;
public LeveledQueue(uint numPriorities)
{
queues = new Queue[numPriorities];
for(int i = 0; i < numPriorities; i++)
queues[i] = Queue.Synchronized(new Queue());
}
public void AddItem(uint priority, object item)
{
if (priority < queues.Length)
queues[priority].Enqueue(item);
}
public object GetHighestPriorityItemFast()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
lock (q.SyncRoot) // same lock as the Dequeue/
Enqueue use?
{
if (q.Count 0)
return q.Dequeue();
}
}
return null;
}
public object GetHighestPriorityItemSlow()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
try
{
object ret = q.Dequeue();
return ret;
}
catch (InvalidOperationException) { }
}
return null;
}
}
static void Main(string[] args)
{
LeveledQueue lq = new LeveledQueue(16);
// worst case will be when they have no data
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPriorityItemFast();
}
sw.Stop();
Console.WriteLine("Fast call used {0} seconds for 4k",
sw.Elapsed.TotalSeconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPriorityItemSlow();
}
sw.Stop();
Console.WriteLine("Slow call used {0} seconds for 4k",
sw.Elapsed.TotalSeconds);
}
}
}