views:

57

answers:

2

I have a worker thread that is vital for my application.
It is created with new Thread( method ).Start(); I don't join it, I just expect that is runs as long as my program runs.
However, it can happen that there is an exception caught on this thread; and as a consequece the thread will (beside some last logging) shutdown. A recovery is not possible for this critical error. Since the thread is vital for the app, it has to shutdown, too.

Now my question is: How can I monitor the state of my thread?

Would you

  • Poll the IsAlive property?
  • rethrow the caught exception and work with AppDomain.CurrentDomain.UnhandledException?
  • implement an event that will signal the end of my background thread?
  • use a BackgroundWorker, which implements RunWorkerCompleted? (But is a BackgroundWorker really the right choice for long running threads?)
  • something completley different?

EDIT:
Right now, I solved the problem by calling Application.Exit() -> crash early and often. That's an option, too :)

+2  A: 

Why don't you wrap your main thread routine like this:

 void ThreadStart()
 {
       try 
       {
            ThreadImplementation();           
       }
       catch (Exception e)
       { 
            mainForm.BeginInvoke(OnBackgroundThreadException, e);
       }
 }

This will make sure you get a message on the application's main thread whenever the thread does an abnormal shutdown. You don't need to poll anything. A BackgroundWorker is typically useful when you need to talk back to the UI thread asynchronously. (I.E. progress updates).

jdv
But I need a reference to a control - only for this purpuse :/
tanascius
A control is a convenient way to execute code on the UI thread. Not neccesarily the only way. Usually you need to switch back at some point, I tend to prefer ASAP.
jdv
+2  A: 

At the end of your thread's exception handler, invoke a callback method on your main thread and restart the worker:

public delegate void AbnormalExitDelegate(object errorArgs);

class Boss
{
    Worker worker;
    void Start()
    {
        worker = new Worker();
        worker.AbnormalExitCallback = new AbnormalExitDelegate(AbnormalExit);
        Thread workerThread = new Thread(worker.DoWork);
        workerThread.Start();
    }
    public void AbnormalExit(object errorArgs)
    {
        Start();
    }
}
class Worker
{
    public AbnormalExitDelegate AbnormalExitCallback;
    public void DoWork()
    {
        try
        {
           // do work here
        }
        catch (Exception ex)
        {
            // pass stuff back, like the exception
            AbnormalExitCallback(ex);
        }
    }
}
ebpower