Skip to main content
 首页 » 编程设计

c#之跳过已在使用的锁定部分

2024年01月28日33cloudgamer

我有一个关键部分,它只执行一次但被许多场景调用。我怎样才能执行这个线程过程并跳过所有其余的调用?

提前致谢。

请您参考如下方法:

// 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 
}