0

I have a thread:

Thread mthread = new Thread(new ThreadStart(thread_main));
mthread.Start();

It starts the function thread_main

void thread_main()
{
    if (BotSuite.ImageLibrary.Template.Image(screendata, invdata).IsEmpty)
    {
        throw new Exception();
    }
}

This exception should be caught in the main thread! I added a line in the button event handler.

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ErrorHandler);

it works great if the exception is in the main thread, but if it's in the mthread nothing happens!

How can I fix that?

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
coolerfarmer
  • 216
  • 1
  • 4
  • 12
  • 2
    Consider using tasks instead of threads; they can report asynchronous failure. – SLaks Mar 12 '14 at 14:37
  • Possible duplicate: http://stackoverflow.com/questions/188977/catching-exceptions-from-another-thread – Luc Morin Mar 12 '14 at 14:38
  • I have read this, but it didn't help me! @SLaks how do I do this? I haven't really used tasks before! May you give me a short example as answer, please! – coolerfarmer Mar 12 '14 at 14:39
  • About using Task: http://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread – Luc Morin Mar 12 '14 at 14:40

1 Answers1

0

You can use Backroundworker if you are using an older Visual Studio or don't want to use Tasks.

    var worker = new BackgroundWorker();
    worker.DoWork += WorkerDoWork;
    worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
    worker.RunWorkerAsync();

    private static void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        throw new Exception("my exception");
    }

    private static void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            //error handling
        }
    }
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51