What is the best way of getting messages from many threads onto a queue and have a separate thread processing items of this queue one at a time?
I am frequently using this pattern when trying to disconnect activities from many threads.
I am using a BlockingCollection for this as shown in a code extract below:
// start this task in a static constructor
Task.Factory.StartNew(() => ProcessMultiUseQueueEntries(), TaskCreationOptions.LongRunning);
private static BlockingCollection<Tuple<XClientMsgExt, BOInfo, string, BOStatus>> _q = new BlockingCollection<Tuple<XClientMsgExt, BOInfo, string, BOStatus>>();
/// <summary>
/// queued - Simple mechanism that will log the fact that this user is sending an xMsg (FROM a user)
/// </summary>
public static void LogXMsgFromUser(XClientMsgExt xMsg)
{
_q.Add(new Tuple<XClientMsgExt, BOInfo, string, BOStatus>(xMsg, null, "", BOStatus.Ignore));
}
/// <summary>
/// queued - Simple mechanism that will log the data being executed by this user
/// </summary>
public static void LogBOToUser(BOInfo boInfo)
{
_q.Add(new Tuple<XClientMsgExt, BOInfo, string, BOStatus>(null, boInfo, "", BOStatus.Ignore));
}
/// <summary>
/// queued - Simple mechanism that will log the status of the BO being executed by this user (causes the red square to flash)
/// </summary>
public static void LogBOStatus(string UserID, BOStatus status)
{
_q.Add(new Tuple<XClientMsgExt, BOInfo, string, BOStatus>(null, null, UserID, status));
}
/// <summary>
/// An endless thread that will keep checking the Queue for new entrants.
/// NOTE - no error handling since this can't fail... :) lol etc
/// </summary>
private static void ProcessMultiUseQueueEntries()
{
while (true) // eternal loop
{
Tuple<XClientMsgExt, BOInfo, string, BOStatus> tuple = _q.Take();
// Do stuff
}
}
This works fine - so I thought - until the Performance Wizard in VS2010 started to highlight the _q.Take() row as the highest contention line in my code!
Note I have also used a standard ConcurrentQueue with a ManualResetEvent combination and each time I insert an item onto the queue I signal the resetevent allowing the worker thread to examine and process the Queue but this also had the same net effect of being highlighted on the .WaitOne() method...
Are there other ways of solving this common pattern of having many threads adding objects into a concurrent queue - and have a single thread ploughing its way through the items one at a time and in its own time...
Thanks!!