views:

1150

answers:

2

In .net 3.5

trying to ThreadPool.QueueUserWorkItem(a=> {Work()}); when the ThreadPool has no available threads caused BeginInvoke lock up.

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(); }
   }
}

How can I make the BeginInvoke use a non-pooled thread?

+5  A: 

You can't. It sounds like you are vastly over-using the pool. Perhaps consider a throttled queue / custom thread pool (i.e. a synchronized producer/consumer queue)?

(don't increase the pool size; that is almost always the wrong approach to take)

Marc Gravell
My problem really only exists with my test harness (which is abusing threadpool), which is attempting to act as a LoadTester against this code
BozoJoe
+1  A: 

Why don't you remove BeginInvoke and do your call synchronous as you're already in a thread there? Is there really a need for async execution in the thread?

ssg
I need to be able to timeout the called routine, to allow the controlling system to move down a different code path quickly.
BozoJoe
Then spawn Work() in a thread rather than threadpool? I don't think ThreadPool has a way of "auto-grow" since that kills its purpose, that's why I'm offering workarounds.
ssg