Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active January 2, 2016 14:39
Show Gist options
  • Save rogeralsing/8318627 to your computer and use it in GitHub Desktop.
Save rogeralsing/8318627 to your computer and use it in GitHub Desktop.
fast mailbox
public class Mailbox
{
private static class MailboxStatus
{
public const int Idle = 0;
public const int Busy = 1;
}
private readonly ConcurrentQueue<Envelope> _queue = new ConcurrentQueue<Envelope>();
private volatile bool _hasUnScheduledMessages;
private int _status;
public void Run(object state)
{
Envelope envelope;
while (_queue.TryDequeue(out envelope))
{
//insert code here
}
Interlocked.Exchange(ref _status, MailboxStatus.Idle);
if (_hasUnScheduledMessages)
{
_hasUnScheduledMessages = false;
Schedule();
}
}
public void Post(Envelope envelope)
{
_hasUnScheduledMessages = true;
_queue.Enqueue(envelope);
Schedule();
}
private void Schedule()
{
//only schedule if we idle
if (Interlocked.Exchange(ref _status, MailboxStatus.Busy) == MailboxStatus.Idle)
{
ThreadPool.QueueUserWorkItem(Run);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment