有什么方法可以确定等待锁定C#的线程数吗? [英] Is there any way to determine the number of threads waiting to lock in C#?

查看:218
本文介绍了有什么方法可以确定等待锁定C#的线程数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lock语句在C#中使用简单锁定.有什么方法可以确定有多少其他线程正在等待获取该对象的锁?我基本上想将等待锁定的线程数限制为5.如果第六个线程需要获得锁定,我的代码将引发异常.

I'm using simple locking in C# using the lock statement. Is there any way to determine how many other threads are waiting to get a lock on the object? I basically want to limit the number of threads that are waiting for a lock to 5. My code would throw an exception if a sixth thread needs to get a lock.

推荐答案

这可以通过Semaphore类轻松实现.它将为您计数.请注意,在下面的代码中,我使用信号量对等待资源的线程数进行了非阻塞检查,然后使用普通的lock来实际序列化对该资源的访问.如果有5个以上的线程在等待资源,则会引发异常.

This can be easily accomplished via the Semaphore class. It will do the counting for you. Notice in the code below that I use a semaphore to do a non-blocking check of the number of threads waiting for the resource and then I use a plain old lock to actually serialize access to that resource. An exception is thrown if there are more than 5 threads waiting for the resource.

public class YourResourceExecutor
{
  private Semaphore m_Semaphore = new Semaphore(5, 5);

  public void Execute()
  {
    bool acquired = false;
    try
    {
      acquired = m_Semaphore.WaitOne(0);
      if (!acquired)
      {
        throw new InvalidOperationException();
      }
      lock (m_Semaphore)
      {
        // Use the resource here.
      }
    }
    finally
    {
      if (acquired) m_Semaphore.Release();
    }
  }
}

此模式有一个显着的变化.您可以将方法的名称更改为TryExecute,并让它返回bool,而不是引发异常.完全取决于您.

There is one notable variation of this pattern. You could change the name of the method to TryExecute and have it return a bool instead of throwing an exception. It is completely up to you.

请记住,锁表达式中使用的对象不是.它仅用作同步代码块的标识符.使用相同对象获取锁的所有代码块都将被有效地序列化.这是被锁定"的代码块,而不是lock表达式

Remember that the object used in the lock expression is not the subject of the lock. It merely serves as an identifier for a synchronized block of code. Any code blocks that acquire locks using the same object will effectively be serialized. It is the code block that is being "locked", not the object used in the lock expression

这篇关于有什么方法可以确定等待锁定C#的线程数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆