基于标志的锁定

Lock based on a flag

我想根据 App 配置中的 flag 锁定几行代码。因此,基于 flag 我 运行 应用程序是否异步。所以我需要通过检查 flag 来锁定几行代码的执行。所以我需要写重复的代码。下面是示例

if (flag) {
    lock(dataLock){
        //few lines of code
    }
} else {
    //repeat the above code gain here (few lines of code)
}

有没有其他方法可以保存我重复的代码。

使用 Monitor.Enter 而不是 Lock() {} ?使用 if 语句进入和退出。

您可以在锁内甚至在 else 语句内使用您的外包代码调用函数。这至少会减少您的开销和重复代码。

if(flag==true){
    lock(dataLock){
        fewLines();
    }
}else{
    fewLines();
}

[...]

public void fewLines(){
   // put your few lines here.
}

那将 运行 来自锁定上下文的函数。

if (flag)
    Monitor.Enter(dataLock);

// few lines of code

if (Monitor.IsEntered(dataLock))
    Monitor.Exit(dataLock);

Monitor.Enter 方法最好,但您也可以这样做:

Action fewLinesOfCode = () =>
{
    //few lines of code
};

if (flag)
{
    lock (dataLock)
    {
        fewLinesOfCode();
    }
}
else
{
    fewLinesOfCode();
}