I’m looking for a good method of tracking (counting) which workers have failed when queued with a Threadpool and using WaitHandle.WaitAll() for all threads to finish.
Is Interlocking a counter a good technique or is there a more robust strategy?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Okay, here’s an approach that you could take. I’ve encapsulated the data that we want to track into a class
TrackedWorkers. There is a constructor on this class that enables you to set how many workers will be working. Then, the workers are launched usingLaunchWorkerswhich requires a delegate that eats anobjectand returns abool. Theobjectrepresents the input to the worker and theboolrepresents success or failure depending ontrueorfalsebeing the return value, respectively.So basically what we do we have an array to track worker state. We launch the workers and set the status corresponding to that worker depending on the return value from the worker. When the worker returns, we set an
AutoResetEventandWaitHandle.WaitAllfor all theAutoResetEventsto be set.Note that there is an nested class to track the work (the delegate) the worker is supposed to do, the input to that work, and an
IDused to set the statusAutoResetEventcorresponding to that thread.Note very carefully that once the work is done we are not holding a reference to the work delegate
funcnor to theinput. This is important so that we don’t accidentally prevent stuff from being garbage collected.There are methods for getting the status of a particular worker, as well as all the indexes of the workers that succeeded and all the indexes of the workers that failed.
One last note: I do not consider this code production ready. It is merely a sketch of the approach that I would take. You need to take care to add testing, exception handling and other such details.
Sample usage:
The above program is going to launch sixty-four threads. The
ith thread has the task of adding the numbersiand2 * iand printing the result to the console. However, I have added a random amount of sleep (less than one second) to simulate busyness and I flip a coin to determine success or failure of the thread. Those that succeed print the sum they were tasked with and returntrue. Those that fail print nothing and returnfalse.Here I have used