Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active January 2, 2016 13:59
Show Gist options
  • Save rogeralsing/8314112 to your computer and use it in GitHub Desktop.
Save rogeralsing/8314112 to your computer and use it in GitHub Desktop.
Is this safe?
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