Duplicate: How to catch exceptions from ThreadPool.QueueUserWorkItem?
I host several delegates in .Net ThreadPool for a large number of independent remote calls, which are themselves called several databases and other autonomous resources. By queuing these calls in ThreadPool, I can run them at the same time and minimize the overall delay.
private void CompleteAndQueuePayLoads(IEnumerable<UsagePayload> payLoads) { List<WaitHandle> waitHndls = new List<WaitHandle>(); foreach (UsagePayload uPyLd in payLoads) { ManualResetEvent txEvnt = new ManualResetEvent(false); UsagePayload uPyLd1 = uPyLd ; ThreadPool.QueueUserWorkItem( delegate { if (!uPyLd1 .IsComplete) // IEEDAL.GetPayloadReadings is long running DB call try { IEEDAL.GetPayloadReadings(uPyLd1 ); } catch (IEEAccessException iX) { log.Write(log.Level.Error, "IEEWSDAL.CompleteAndQueuePayLoads " + " Delegate Failed " + iX.Message, iX); txEvnt.Set(); throw; // this causes parent thread to crash! // was going to try Thread.Abort next ... // Thread.CurrentThread.Abort(); } UsageCache.PersistPayload(uPyLd1 ); SavePayLoadToProcessQueueFolder(uPyLd1 ); txEvnt.Set(); }); waitHndls.Add(txEvnt); } util.WaitAll(waitHndls.ToArray()); //To waitone on > 64 waithandles }
But the whole batch should be processed transactionally, IE, the output of the parent thread should be allowed only if all child threads were successful. I coded the child thread to throw a custom exception when it failed, but I found that this causes the parent thread to crash because these exceptions cannot be "caught" in the parent thread ...
I read about the UnHandledExceptionEvent CLR error when this happens, but I need to "handle" this exception in a method in which these child threads are queued and thrown to control the immediate subsequent processing based on success from child triads ... How do I get this to do?
Charles Bretana Mar 20 '09 at 22:43 2009-03-20 22:43
source share