I'm working in a legacy project that has this exception handling code in many methods.
catch(ThreadAbortException e)
{
...
}
I don't see anywhere in the project Thread.Abort() or Thread.Interrupt() calls. Is it safe to delete all these ThreadAbortException handling or it is some other way that can be raised.
Well if answering specifically your question I would say that it would be better not to delete these exception handlers as it’s most likely that they were added by some developer trying to solve a problem. And I think there was a reason to add those handlers so if you just remove this code it can lead to appearing of some bugs again in the future.
Regarding the ThreadAbordException: I know for sure that it can be throwed not only with calling Thread.Abort() method when you are debugging (it might be a bug in VS, I’m not sure) and it forces your program to just crash silently. So depending on what’s inside of those handlers it could be possible that a developer was trying to solve such problem.
Also remember that you could be invoking methods of third-party libraries, web-services etc. in a separate thread, too. I’m not sure if they can throw such an exception but that’s a possible case to consider.
Official docs: "The exception that is thrown when a call is made to the Abort method." If you are completely sure there are no calls to Thread.Abort then you might as well erase those catch blocks.
EDIT: Be mindful that your code may be running in the context of an external app that may call Thread.Abort on your threads.
Not that it matters anyway as a ThreadAbortException can't really be handled as the CLR itself will rethrow it to actually kill the thread ASAP.
"Actually yes, a ThreadAbortException is special. Even if you handle it, it will be automatically re-thrown by the CLR at the end of the try/catch/finally. (As noted in the comments, it can be suppressed with ResetAbort but by that point the code smells like rotten fish.)"
- Read this question for more details: ThreadAbortException
Is the project running on a main thread and spinning up background worker threads? If the main thread exits while background threads are running, a ThreadAbortedException can occur on the background threads.
The catch statement could specifically handle this scenario, where no error actually occurred on the background thread, in a different manner than any other exception.
Related
I've inherited some service code and I'm trying to track down an issue with service crashes. I've found the following code in many places:
catch (ThreadAbortException)
{
throw;
}
However, I can't find any calls to Thread.Abort() or Thread.Kill() in any parts of the project (or related projects).
Is Thread.Abort() ever implicitly called by the .NET runtime, or does that exception exist only to catch calls that a developer makes? I'm trying to narrow my error avenues and I'm not very experienced with threads in C#. I'm trying to determine whether the catch block I've shown is ever actually hit if Thread.Abort() is never actually called in my codebase.
Thanks!
Edit: I want to clarify - I know that .NET can kill threads, but I was wondering if it specifically calls Thread.Abort() or whether it uses some other means (as the ThreadAbortException is only called on Thread.Abort().
Catch/throw without doing anything about it seems pointless.
These errors are common in ASP.NET-- it means a redirect that ended the response, eg. ASP.NET Response.Redirect( ) Error
or it means a worker process was killed by casinni/iis/aspnet for it's own mysterious reasons, maybe worker process recycles, etc.
It normally doesn't indicate a programming error.
Calling Thread.Abort() in multi-threaded apps appears to be a bad idea in most cases and other answers on SO speak to that better than I could.
Edit: I want to clarify - I know that .NET can kill threads, but I was
wondering if it specifically calls Thread.Abort() or whether it uses
some other means (as the ThreadAbortException is only called on
Thread.Abort().
If you're really interested to see whether (and where) it does that, refer to .NET Reference Source, it's pretty complete. Specifically, it shows that Thread.Abort is referenced at these places.
I want to log uncaught exceptions in a C# windows store project.
For code executing in the UI thread I can use the Windows.UI.Xaml.Application.Current.UnhandledException event, but exceptions from code executing in the tread pool do not trigger that event.
I could try to ensure all of the 'RunAsync' calls are wrapped to log uncaught exceptions, but it's very easy to accidentally bypass that solution. Is there something for this that's already in the API?
I'm not sure if there is something available, but you could create your own version of RunAsync, that takes an action to execute and wraps it in a try/catch block before executing it using the platform version of the RunAsync and just keep making sure this is the only method you use to run things in the background.
Other than that - debugging with breaks on all exceptions enabled (Alt+Ctrl+E, check all) should help you find the problem areas.
How do you schedule code to run as a Threadpoolthread? In case you are using Tasks, check the UnobservedException Event on the TaskScheduler
System.Threading.Tasks.TaskScheduler.UnobservedTaskException +=new EventHandler<UnobservedTaskExceptionEventArgs>(...);
There are two unexpected exception handlers that I'm aware of at this point:
System.Threading.Tasks.TaskScheduler.UnobservedTaskException for exceptions, stored in a task, that are not accessed before the task is garbage collected.
Application.Current.UnhandledException for exceptions propagating out of the UI thread.
I'm not aware of anything to catch exceptions propagating out of the thread pool, yet.
I am new to multithreaded application. I have few doubts before starting working on it.
Can anyone clear these doubts?
How to handle exceptions in multithreaded application?
If there is any exceptions in any 1 thread, will the whole application will come
down? or all other threads will continue?
How to handle exceptions in multithreaded application?
The best way is inside the thread, but sometimes eg. (thread pool) this is hard. To handle unhandled exceptions depends on the type of application:
WPF: Use Application.DispatcherUnhandledException
Console or Service: Use AppDomain.UnhandledException
ASP.NET, WinForms, ... have their own mechanisms.
But consider: especially while developing to allow the default handling and falling into the debugger (adding if (Debugger.IsAttached) { Debugger.Break(); } can be very helpful to define a permanant breakpoint
If there is any exceptions in any 1 thread, will the whole application will come down?
It depends. In ASP.NET: No (if debugging is enabled you'll see a Yellow Screen of Death, otherwise a 500 server error result); in other hosts: depends (but generally the answer is Yes the process will terminate).
Some of the details of this have changed between .NET versions – typically getting stricter, so you need to do your research. Finally: in .NET 4 certainly, possibly before as well, certain exceptions (eg. StackOverflowException) cannot be caught because there is no reliable way to have consistent process state if they are thrown.
If you are using TPL you can use Aggregate exception. This aggregate exception is a collection of exceptions you can loop through them to see which thread failed to execute more information can be found here. http://msdn.microsoft.com/en-us/library/dd997415.aspx
I'm looking for some guidance on best practices on handling exceptions in events. Currently, when exceptions are thrown in my application, the exception message is displayed in a pop up dialog and then the application restarts after hitting ok. The issue I'm seeing is that a lot of exceptions are occurring in the event handlers of some third party libraries and these exceptions are swallowed and never displayed since they are on a background thread. Here are a few solutions that various people have thought of and I would like to know of any of these are the best approach.
Forward the background thread to the UI thread in every event handler in the application.
Wrap the events in another class which has a try/catch around every method that invokes the event. The catch will then forward the exception to the UI thread if one occurs.
Get access to the third party libraries and put try/catch around where the events are being invoked, which could then be forwarded to the main application by a global event.
Lets discuss your options the way you listed them:
1) Forward the background thread to the UI thread in every event
handler in the application.
You should not and you can't! because:
You can't pretend if that event "which may comes from a third party" starts another background thread
or timer.
The whole point of having background threads is not
to freeze the UI, you will then struggle the user interface by a long execution codes.
2) Wrap the events in another class which has a try/catch around every method that invokes the event. The catch will then forward the exception to the UI thread if one occurs.
The same point as the previous. you can't pretend it that event starts another thread..
3) Get access to the third party libraries and put try/catch around where the events are being invoked, which could then be forwarded to the main application by a global event.
This is a bad choice, really, You should not change that code of third party libraries even if you can. because:
You are not the author for those libraries.
Whenever you want to update the library version or even change the libraries, you have to rewrite there code..
So what you have to do? The answer is some sort of what you are currently doing:
Whenever any exception thrown, log the exception restart your process, and at some point in your process send the logged bugs to your email and then start fixing them.
None of the above. Instead hook up the events on the Application and AppDomain for unhandled exceptions.
AppDomain.CurrentDomain.UnhandledException Event
Application.DispatcherUnhandledException Event
Further Information: The global exception handling event for WPF applications Application.DispatcherUnhandledException fires only for exceptions thrown on the main UI thread. However the AppDomain.CurrentDomain.UnhandledException should fire on any unhandled exception in any thread (unfortunately there is no preventing the application from shutting down after ward it reaches here).
Did some quick research on best practices and found that it is recommend that you manually handle exceptions on the background threads with try\catch block. Read the exception part on this page http://www.albahari.com/threading/ and also take a look at this StackOverflow question Catching unhandled exception on separate threads
If you're hooking the AppDomain.UnhandledException event, then the issue isn't the fact that they might be calling back on a background thread, but rather than the third-party library is explicitly swallowing exceptions thrown by the handlers. This is a badly behaving library, but, since you're writing the event handler code, you can catch the exceptions in the event handler and force the application to shut down.
Since the third-party library can't be stopped by throwing an exception, you can force the thread to terminate by calling:
Thread.CurrentThread.Abort();
Thread.Abort() is generally considered a bad practice, but it's slightly less dangerous here, as you are aborting yourself and therefore won't be injecting the exception into potentially nasty locations (you also know that the thread is not in an unmanaged context, so it will abort right away.) It's still a nasty hack, but the third-party application isn't giving you much choice. ThreadAbortException cannot be 'stopped', so the third-party code will terminate its thread as soon as it reaches the end of its exception handlers (even if they try to swallow it). If the third-party library is really nasty, it might invoke lots of code in its catch or finally blocks, even using dirty tricks to stay alive like launching other threads, but it would have to be pretty malicious to do this.
To get the friendly error message behavior, you can marshal the Exception to your UI thread using a SynchronizationContext or Dispatcher to call your exception-handler display (the easiest way may be to just re-throw the exception; I recommend embedding it as an InnerException so that you don't lose stack trace.)
If you really distrust the library (and don't want to give it the opportunity to stay alive even through its catch and finally blocks), you can explicitly marshal to the UI thread with a blocking invoke (to display your error message in a friendly way) and then call Environment.FailFast() to kill your process. This is a particularly harsh way to terminate (it will not call any cleanup code and literally tears down the process as quickly as possible), but it minimizes the possibility for any potentially damaging side effects if application state has become very corrupted. One possible thing to watch for here is that the UI thread could be blocked by some other UI invocation tied to the third-party code. If this happens, the application will deadlock. Again, this would be a pretty malicious thing for it to do, so you can probably ignore it.
So I know that you shouldn't use
Thread.Abort()
But I've never been given a good explanation. Is there a performance penalty or some hidden gotcha?
I know you can't ignore/swallow the ThreadAbortException (which makes sense)
In addition to all of the other good answers here, let me add that there is no guarantee whatsoever that a call to Thread.Abort will actually abort the thread in question, ever. It is possible (though not particularly easy) to "harden" a thread against being aborted. If, for example, you are aborting a thread because you believe it to be running hostile code then the hostile code could be resisting its own destruction.
If you have a long-running operation involving code that you do not own that must be taken down cleanly, the correct way to do this is to put that code in its own process, not its own thread. (And preferably in a highly security-restricted appdomain in that process.) You can then cleanly kill the process.
In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.
Because if you know that the thread is in some safe state in which it can be aborted, surely you can arrange better communication and have the thread exit cleanly.
The thread could have taken a lock and be in the middle of changing some shared state, and the Thread.Abort will undo the lock and leave the shared state corrupted.
It's easier to hurt yourself. As others have stated it raises an exception in the code, which can occur at any point. This might be fine if you expect this and have coded in a way that elegantly handles this exception at any point but some people dont:
Monitor.Enter(obj);
// some code - if exception is raised here, then the lock isn't released
Monitor.Exit(obj)
IDisposable someCriticalResource = GetResource();
// some code - if exception is raised here, then the object isn't disposed
someCriticalResource.Dispose();
Additionally if you're working with many people on a team unless you have good code reviews you cannot guarantee the quality of the code you'll be working with. Hence it is a good idea to preach the gospal of "no Thread.Abort()" than it is to get people to remember to write code that is robust against exceptions occuring anywhere within that code.
In short.
Any IDisposable object may not be disposed. Any locked object may not be unlocked. Anything that must be 100% performed will never be done.
When you call Thread.Abort() on another thread a ThreadAbortException is injected in the flow of that thread. If you're lucky the code will handled this well and abort in a well defined state. The problem is that you have no way to figure out if you will be lucky in every case, so if you prefer safe over sorry calling Thread.Abort on other threads is not a good idea.
Thread.Abort stops your thread in an uncontrolled fashion.
thread.Abort will throw an exception, which will cause that your thread stops immediatly.
What is wrong with that: in most cases, you want to gracefully stop the operation that you're performing. For instance, if you are executing an ACID operation, you might want to complete the current operation before ending the thread, so that your system remains in a stable state.
Thread.Abort rises an exception in the target thread. Target thread in the meantime can be performing some critical operations and rising an exception can break your application state.