user1121956
user1121956

Reputation: 1961

How to make thread not crashing application

Let's assume I have following console application:

Thread thread = new Thread(new ThreadStart(() => { throw new Exception(); }));
thread.IsBackground = true;
thread.Start();

while (true)
  Console.WriteLine("Hello from main thread");

Is it possible to make entire application not crashing because of background tread's exception (without using try..catch of course)?

Upvotes: 2

Views: 5383

Answers (5)

Johnny Jørgensen
Johnny Jørgensen

Reputation: 29

Using a Task instead does not crash the application

Task.Factory.StartNew(() => { throw new Exception(); });

while (true) Console.WriteLine("Hello from main thread");

Upvotes: -1

Alexander Bortnik
Alexander Bortnik

Reputation: 1289

Attach your unhandled exceptions handler: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

The better way you can achieve desired result (Ok, with try/catch, but only once) with global handler:

    public static void GlobalHandler(ThreadStart threadStartTarget)
    {
        try
        {
            threadStartTarget.Invoke();
        }
        catch (Exception ex)
        {
             //handle exception here
        }
    }

And then start your threads:

        Thread thread = new Thread(o => GlobalHandler(ThreadMethod));
        thread.Start();

P.S. However, really, I don't like idea of catching all exceptions. It is almost never good idea.

Upvotes: 7

igrimpe
igrimpe

Reputation: 1785

Even if you CAN catch unhandled exceptions globally, you shoud be aware that there are some exceptions that you might be able to catch, but not to handle. StackoverflowException might not leave enough stackspace to handle the exception. Same with OutOfMemory. There MIGHT not be enough space for a large object, but there's also a chance that there is no space left at all.
So you usually write code to catch and handle THOSE exceptions that you CAN handle (filenotfound, accessviolation etc) and leave all others to crash your app (better crash than continue in undefined state). The only thing you could do with an unhandled exception: TRY to gracefully close your app (saving some changes, writing an error log or whatever) and THE rethrow the exception.

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

It is not good practice to hide unhanded exception and forget about it, so don't do it.

I am not sure why you don't want to use try/catch but it is the best way to handle the situation, in which case you should fix exception if you can, or at least log it for later review

Upvotes: 0

satnhak
satnhak

Reputation: 9861

You could use a ThreadPool thread.

Upvotes: 0

Related Questions