我有一个关键部分,该部分只能执行一次,但在许多情况下都会被调用。如何执行此线程proc并跳过所有其余的调用?

提前致谢。

最佳答案

// Assuming this uses calls from multiple threads, I used volatile.
volatile bool executed = false;
object lockExcecuted = new object();

void DoSomething()
{
    lock (lockExecuted)
    {
        if (executed) return;
        executed = true;
    }
    // do something
}

10-04 15:13