How can I make sure that exactly one thread will do something?

Viewed 1305

I have multiple threads which add items to a lock-free queue.
The items are then processed by another thread.

In the producer threads, I need to kick off the consumer thread, but only if it's not already running or kicked off.

Specifically:

public void BeginInvoke(Action method)
{
    //This runs on multiple background threads
    pendingActions.Enqueue(method);
    if (ProcessQueue hasn't been posted)
        uiContext.Post(ProcessQueue, null);
}
private void ProcessQueue(object unused)
{
    //This runs on the UI thread.
    Action current;
    while (pendingActions.TryDequeue(out current))
        current();
}

I'm using .Net 3.5, not 4.0. :(

4 Answers
Related