Sometimes when working with .NET you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is Environment.FailFast.
The FailFast method stops your program immediately, ensuring that no further code can execute. As this means that you cannot report the problem directly to the user, this static method includes a parameter, to which you can provide a string containing a status message. This message is recorded in the application event log.
When is this method useful?
One scenario where this method is useful is when your program can enter an unstable state that introduces the risk of data corruption. If this means that it is not possible to continue with the process safely, it may be necessary to exit the program and report an error. Environment.FailFast allows you to kill the process immediately, ensuring that no further code executes.
Another scenario where you can use it is when you have an application that is giving you some weird output. You know it's wrong, but there are just no exceptions bubbling to the surface to help you out. By putting Environment.FastFail you can log an internal exception and hopefully find out where your problem is.
Here is a code sample:
Notice that when you execute this code, only the ‘start’ message is written to the console.