【问题标题】:Implementing lock based on status基于状态实现锁
【发布时间】:2017-08-23 22:14:34
【问题描述】:

如果我有这样的方法:

public class Main()
{
  public void Start()
  {
     if(//Check if another thread already invoked this method and its in processing//)
       DoSomething();
  }

  void DoSomething()
  {
    //Some code in here
  }
}

如何使用锁来检查一个线程是否已经在执行 DoSomething() 然后跳过它?

我知道锁会让其他调用等待,但我想跳过而不是等待并执行。

【问题讨论】:

    标签: multithreading c#-4.0 thread-safety locking


    【解决方案1】:

    你可以使用

    尝试锁定

    布尔tryLock() 仅当调用时它是空闲的时才获取锁。 如果锁可用,则获取锁,并立即返回值为 true。如果锁不可用,则此方法将立即返回值为 false。

    这种方法的典型用法是:

      Lock lock = ...;
      if (lock.tryLock()) {
          try {
              // manipulate protected state
          } finally {
              lock.unlock();
          }
      } else {
          // perform alternative actions
      }
    

    这种用法确保锁在获得时被解锁,并且在未获得锁时不会尝试解锁。 回报: 如果获得了锁则为真,否则为假

    【讨论】:

    • 如果在锁被释放后立即再次调用该方法怎么办?
    • 第一次尝试调用acquire应该得到锁
    猜你喜欢
    • 2011-06-21
    • 2020-08-02
    • 2013-05-27
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多