开发者

How to monitor a vital worker thread

开发者 https://www.devze.com 2022-12-22 02:22 出处:网络
I hav开发者_运维百科e 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.

I hav开发者_运维百科e 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 :)


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).


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);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消