1

我正在检查这段代码,它正在执行类似于 SyncLock的操作,但它们不是等待其他线程,而是跳过代码。

代码是用变量来做的;我想知道是否有一个内置的.net 函数可以做到这一点?

Private _previousValueCount As Integer = 0

Private Sub F()
   If _previousValueCount = 0 Then
       _previousValueCount = 1
       ' ...
       _previousValueCount = 0
   End If
End Sub
4

2 回答 2

2

有很多方法可以做到;一种方法是执行以下操作:

int lockTaken = 0;

...

bool haveLock = false;
try {
    haveLock = Interlocked.CompareExchange(ref lockTaken, 1, 0) == 0;
    if(haveLock) {
       // it was zero, it is now one; you won the lock: do something
    }
} finally {
    if(haveLock) Interlocked.Exchange(ref lockTaken, 0);
}

另一种方法是使用Monitor.TryEnter零超时:

readonly object syncLock = new object();
...
bool haveLock = false;
try {
    Monitor.TryEnter(syncLock, 0, ref haveLock);
    if(haveLock) {
      // you won it; do something
    }
} finally {
    if(haveLock) Monitor.Exit(syncLock);
}
于 2012-08-28T19:24:35.580 回答
1

您可以使用Monitor类来尝试获取任何类型的全局对象的锁定。如果您在某个时间跨度/毫秒内没有获得,您可以随心所欲。

bool acquiredLock = false;
try
{
  Monitor.TryEnter(lockObject, 1000, ref acquiredLock);
  if (acquiredLock)
  {
    // got lock, do something
  }
  else
  {
    // no lock - warning/error/...
  }
}
finally
{
  if (acquiredLock)
     Monitor.Exit(lockObject);  // release lock!
}
于 2012-08-28T19:27:34.080 回答