Last active
January 2, 2016 14:39
-
-
Save rogeralsing/8318627 to your computer and use it in GitHub Desktop.
fast mailbox
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 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