How to control a vital work thread

I have a workflow that is vital to my application.
It was created with the help of. new Thread( method ).Start();I do not join it, I just expect it to work as long as my program works.
However, it may happen that there is an exception in this thread; and, as a result, the flow will (at some last completion of registration) turn off. Recovering this critical error is not possible. Since the thread is vital to the application, it must also shut down.

Now my question is: How can I control the status of my thread?

You

  • Interrogate a property IsAlive?
  • Recover caught exception and work with AppDomain.CurrentDomain.UnhandledException?
  • implement eventthat will signal the end of my background thread?
  • use BackgroundWorkerwhich implements RunWorkerCompleted? (But is BackgroundWorker the right choice for long threads?)
  • something completely different?

EDIT:
Right now, I solved the problem by causing -> Application.Exit()crashing early and often. This is also an option :)

+5
source share
2 answers

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

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

, , . . BackgroundWorker , . ( I.E.).

+2

:

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);
        }
    }
}
+2

All Articles