我如何确保只有一个线程可以执行某些操作?

SLa*_*aks 10 .net c# multithreading thread-safety

我有多个线程将项添加到无锁队列.
然后由另一个线程处理这些项目.

在生产者线程中,我需要启动消费者线程,但前提是它尚未运行或启动.

特别:

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();
}
Run Code Online (Sandbox Code Playgroud)

我使用的是.Net 3.5,而不是4.0.:(

SLa*_*aks 2

我创建了以下类来执行此操作:

///<summary>Ensures that a block of code is only executed once at a time.</summary>
class Valve
{
    int isEntered;  //0 means false; 1 true

    ///<summary>Tries to enter the valve.</summary>
    ///<returns>True if no other thread is in the valve; false if the valve has already been entered.</returns>
    public bool TryEnter()
    {
        if (Interlocked.CompareExchange(ref isEntered, 1, 0) == 0)
            return true;
        return false;
    }

    ///<summary>Allows the valve to be entered again.</summary>
    public void Exit()
    {
        Debug.Assert(isEntered == 1);
        isEntered = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

readonly Valve valve = new Valve();
public void BeginInvoke(Action method)
{
    pendingActions.Enqueue(method);
    if (valve.TryEnter())
        uiContext.Post(ProcessQueue, null);
}
private void ProcessQueue(object unused)
{
    //This runs on the UI thread.
    Action current;
    while (pendingActions.TryDequeue(out current))
        current();
    valve.Exit();
}
Run Code Online (Sandbox Code Playgroud)

这种模式安全吗?
有一个更好的方法吗?
班级有更正确的名称吗?