Last active
January 2, 2016 13:49
-
-
Save rogeralsing/8313019 to your computer and use it in GitHub Desktop.
Concurrent mailbox C#.
Need help in how to schedule the run handler in the Post method, with the criteria that it may not be scheduled concurrently.
"run" may only run in one thread at a time..
The current implementation works but hogs the system when there are no messages in any of the queues.
And I'd like this to be as efficient as possible, s…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConcurrentQueueMailbox : Mailbox | |
{ | |
private ConcurrentQueue<Envelope> userMessages = new ConcurrentQueue<Envelope>(); | |
private ConcurrentQueue<Envelope> systemMessages = new ConcurrentQueue<Envelope>(); | |
private WaitCallback run = null; | |
public ConcurrentQueueMailbox() | |
{ | |
run = new WaitCallback(_ => | |
{ | |
while (systemMessages.Count > 0) | |
{ | |
Envelope envelope = null; | |
if (systemMessages.TryDequeue(out envelope)) | |
{ | |
this.OnNext(envelope); | |
} | |
} | |
while (userMessages.Count > 0) | |
{ | |
Envelope envelope = null; | |
if (userMessages.TryDequeue(out envelope)) | |
{ | |
this.OnNext(envelope); | |
} | |
} | |
//I'd like to remove this in favor for | |
//doing this in the post method | |
ThreadPool.QueueUserWorkItem(run); | |
}); | |
ThreadPool.QueueUserWorkItem(run); | |
} | |
public override void Post(Envelope envelope) | |
{ | |
if (envelope.Payload is SystemMessage) | |
{ | |
systemMessages.Enqueue(envelope); | |
} | |
else | |
{ | |
userMessages.Enqueue(envelope); | |
} | |
//I'd like to schedule this mailbox to run again | |
//but it may not be scheduled more than one time concurrently | |
// | |
//I'm aware of TPL DataFlow etc, but they are far too slow | |
// | |
//????? | |
//{ | |
// ThreadPool.QueueUserWorkItem(run); | |
//} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment