首页 > 解决方案 > 基于标志的锁定

问题描述

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

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

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

标签: c#multithreadingif-statementlocking

解决方案


if (flag)
    Monitor.Enter(dataLock);

// few lines of code

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

推荐阅读