跳过已在使用的锁定部分

Var*_*dey 1 c# multithreading

我有一个只执行一次但被许多场景调用的关键部分。如何执行此线程过程并跳过所有其余调用?

提前致谢。

Ken*_*rey 5

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