在执行异步编程时正确设置变量

时间:2018-05-17 20:15:37

标签: c# multithreading

我有一个具有属性的模型

public static class CheckerClass
{
    public static bool checkFlag { get; set; }
}

我有一个设置上述属性的方法

public async Task test()
{
    checkFlag = true;
    await SomeotherService1.Method1();
}

SomeotherService1.cs

Method1(){
  SomeotherService2.Method2(somedata);
}

//有更多来电Method5(),所以我无法发送一个属性来查看是否从test()调用了它。

SomeotherService5.cs

Method5(SomeModel someData)
{
    if(checkFalg)
    {
        checkFlag = false;
        //execute methods
    }
    else
    {
        //execute some other methods
    }
}

我有一些同时运行test()Method()的线程[假设thread1] 和一些只运行Method() [假设thread2]的线程。

当thread1运行时,它将checkFlag设置为true,Method()中的if条件将会执行。

但是,当thread2同时运行时,checkFlag仍为真,这是不正确的。我该如何解决这个问题。

thread2应始终具有checkFlag = false;

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您应该同步对您的flag属性的访问。这可以通过多种方式完成,但最简单的可能是简单的锁定:

创建同步字段:

private readonly object _sync = new object();

然后执行以下检查:

lock(_sync)
{
    if(checkFlag)
         return;
    checkFlag = true;
}

编辑:重读您的问题,我不确定我是否正确理解您的需求。特别是“thread2应该总是有checkFlag = false;”而且你将checkFlag作为模型的一个属性,但你在任何地方使用它都会让我感到困惑。您的Method不仅应包含其他变量吗?你提出问题的方式,它似乎与线程问题无关?确实

public async Task test(){
    await SomeotherService.Method(someData, true);
 }

SomeotherService.cs

Method(SomeModel someData, bool check = false){
    if(check ){
       //execute methods
    }
    else{
       //execute some other methods
    }
 }