简体   繁体   中英

Locking mechanism in c#

I want to implement a lock mechanism so only one thread can run a block of code. But I don't want other threads to wait on lock object, they should do nothing if it's locked. So it's a little different than standard lock mechanism.

if (block is not locked)
{
    // Do something
}
else
{
    // Do nothing
}

What is the best way to do this in C#.

Then instead of using locks, you should use the Monitor Class .

Excerpt: Monitor.TryEnter() example from MSDN

// Request the lock. 
if (Monitor.TryEnter(m_inputQueue, waitTime))
{
   try
   {
      m_inputQueue.Enqueue(qValue);
   }
   finally
   {
      // Ensure that the lock is released.
      Monitor.Exit(m_inputQueue);
   }
   return true;
}
else
{
   return false;
}

As Marc Gravell noted, waitTime can optionally be zero. Depending on different scenarios 10ms or 100ms might be more effective.

使用Monitor.TryEnter( lockObject, timespan) {....}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM