I've inherited a multi-threaded Windows Service (C#, .NET) with no support for unhanded exceptions. The service is using multiple threads to collect data from telemetry devices for analysis. A thread in this service could run for 24 hours or more. I'm struggling with how to tell the main thread that a thread is experiencing problems and needs to recycle. Here's a simplified view of the code:
class Program
{
static void Main(string[] args)
{
var workerObject = new WorkerObject();
var workerThread = new Thread(workerObject.DoWork);
workerThread.Start()
}
}
class WorkerObject
{
//todo: My fields and properties go here
public void DoWork()
{
const int timeout = 100;
//todo: setup wait handles here
try
{
//Start monitoring channels for this device
while (true)
{
// Wait on any waithandle or timeout once per decisecond.
int channelIndex = WaitHandle.WaitAny(waitHandles, timeout, false);
//todo: process incoming data for this channel
}
}
//Catch all exceptions so we can notify mommy that we're in a bad way
catch (Exception ex)
开发者_如何学编程 {
//todo: log anything that can help us figure this problem out
//How do I tell the main thread I've failed
}
finally
{
//But of course we want to clean up after ourselves
}
}
}
Is this even the best .NET threading mechanism to use? Should I be using Async Delegates or Task Parallel Library instead?
I had a similar requirement recently. I don't think that you can rely on the child threads telling the parent when they are bad. What if they are caught in an infinite loop or deadlocked for some reason? I settled in on a 'watch dog' approach. Each of the child thread needed to send a 'heartbeat' back to the main thread. If this signal was not received, then the thread was assumed 'dead' and an action could be taken. Here is a post about the architecture I settled in on:
http://blog.bobcravens.com/2009/08/monitored-watchdog-asynchronous-process-in-c/
Hope this helps.
Bob
Daniel Moth has blogged a lot about multithreading and more recently the Parallel Tasks support in .net 4.0. It's a great resource, http://www.danielmoth.com and very interesting. I'd definitely check that out.
I'm not sure if this helps but I worked on a "Report Runner" Windows Service which takes jobs from a queue and then schedules the work on the ThreadPool; this worked well because if a "Report" fails, I just log the error and exit the function and since it was scheduled in the ThreadPool it just gets returned to the pool to run more reports. Using the ThreadPool avoids the code needed to manage spinning up a new thread if the code you're running fails.
精彩评论