Last active
January 2, 2016 13:59
-
-
Save rogeralsing/8314112 to your computer and use it in GitHub Desktop.
Is this safe?
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 ConcurrentQueue<Envelope> queue = new ConcurrentQueue<Envelope>(); | |
private int scheduled = 0; | |
private volatile bool hasUnScheduledMessages = false; | |
private WaitCallback run; | |
public Mailbox () | |
{ | |
run = new WaitCallback(Run); | |
} | |
public void Run(object state) | |
{ | |
Envelope tmp; | |
while (queue.TryDequeue(out tmp)) | |
{ | |
//code to process each message | |
} | |
scheduled = 0; | |
if (hasUnScheduledMessages) | |
{ | |
hasUnScheduledMessages = false; | |
Schedule(); | |
} | |
} | |
public void Post(Envelope m) | |
{ | |
hasUnScheduledMessages = true; | |
queue.Enqueue(m); | |
Schedule(); | |
} | |
private void Schedule() | |
{ | |
//only schedule if we idle | |
if (Interlocked.Exchange(ref scheduled, 1) == 0) | |
{ | |
ThreadPool.QueueUserWorkItem(run); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment