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.Collecti ons.Generic;
using System.Text;
using System.Collecti ons;
using System.Diagnost ics;
namespace QueueDemoApp
{
class Program
{
class LeveledQueue
{
Queue[] queues;
public LeveledQueue(ui nt numPriorities)
{
queues = new Queue[numPriorities];
for(int i = 0; i < numPriorities; i++)
queues[i] = Queue.Synchroni zed(new Queue());
}
public void AddItem(uint priority, object item)
{
if (priority < queues.Length)
queues[priority].Enqueue(item);
}
public object GetHighestPrior ityItemFast()
{
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 GetHighestPrior ityItemSlow()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
try
{
object ret = q.Dequeue();
return ret;
}
catch (InvalidOperati onException) { }
}
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.GetHighestPr iorityItemFast( );
}
sw.Stop();
Console.WriteLi ne("Fast call used {0} seconds for 4k",
sw.Elapsed.Tota lSeconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPr iorityItemSlow( );
}
sw.Stop();
Console.WriteLi ne("Slow call used {0} seconds for 4k",
sw.Elapsed.Tota lSeconds);
}
}
}