views:

614

answers:

3

Observe the following pseudo:

ManualResetEvent[] resetEvents = new ManualResetEvent[operations.Count];

for( int i = 0; i < operations.Count; i++ )
{
  resetEvents[i] = new ManualResetEvent(false);
  ThreadPool.QueueUserWorkItem(new WaitCallback(timeConsumingOpHandler), resetEvents[i]);
}

WaitHandle.WaitAll(resetEvents);

In the case that an exception occurs inside one of the pooled threads, my ASP.NET WebApp is deadlocking. No exception information is being passed on the response stream. I'm seeking suggestions to prevent this. A fixed timeout is acceptable. Assume that the timeConsumingOpHandler Set()s the WaitHandle.

The entire timeConsumingOpHandler is wrapped in a try-catch-finally block where the WaitHandle is Set() during the finally section. None the less, deadlock occurs.

A: 

Any blocking operation is a potential deadlock. There are ways that you can minimize or virtually eliminate the chance of a deadlock ever occurring (if you always make sure that your synchronized operations finish in a finite amount of time) but in the general case you can not just assume there's a safe way to prevent deadlocks.

A timeout goes a long way in ensuring that your application does not deadlock, but you'll then have stalling, and you'll need to recover from a timeout in an exceptional way. The same program flow doesn't apply any more.

If you have threads that throw exceptions check the Debug > Output window in Visual Studio it seems to always catch an exception even though the debugger fails to break when dealing with multiple threads.

It's looks like you're splitting up work into separate threads, to achieve parallelism. Why do you need this in a ASP.NET application?

John Leidegren
+1  A: 

Are you certain you are in deadlock? In .NET 2.0, unhandled exceptions in the ThreadPool terminate the process.

You should not use the ThreadPool in ASP.NET applications. ASP.NET itself uses the ThreadPool to service requests, so you are competing for the same set of threads. If you must have asynchronous execution, use an asynchronous delegate.

Sunlight
A good tip. Thanks.
Kivin
A: 

You might want to look at a custom CLR host on MSDN that Joe Duffy developed to provide automatic deadlock detection.

Matt Davison