如果ThreadPool已满,则如何使Action.BeginInvoke生成非线程池线程

Boz*_*Joe 1 c# multithreading asynchronous .net-3.5

在.net 3.5

尝试ThreadPool.QueueUserWorkItem(a=> {Work()});在ThreadPool没有可用线程时导致BeginInvoke锁定.

void Work()
{
   Action executor = () = { DoSomething(); };
   IAsyncResult result = executor.BeginInvoke(null, null);

   using (WaitHandle hWait = result.AsyncWaitHandle)
   {
      if (hWait.WaitOne(timeoutMilliseconds))
      {
        executor.EndInvoke(result);
      }
      else
      {  throw new ImDyingException(); }
   }
}
Run Code Online (Sandbox Code Playgroud)

如何使BeginInvoke使用非池化线程?

Mar*_*ell 5

你不能.听起来你大大超过了游泳池.也许考虑一个受限制的队列/自定义线程池(即同步的生产者/消费者队列)?

(不要增加池大小;这几乎总是错误的方法)