Search code examples
.netmultithreadingfileloadexception

Unhandled FileLoadException that I think I'm handling


I have a thread that get I initialize like this:

Utility.Log("1");

myThread = new Thread(new ThreadStart(delegate
{
    Utility.Log("2");

and then the rest of the thread's execution. The weird thing is, despite that whole thing being wrapped in a try/catch, I'm only seeing a 1 in my log file (no 2), and I'm getting an unhandled System.IO.FileLoadException. I've tried also wrapping the entire body of the delegate in a try/catch, but I'm still getting that exception, and the Event Viewer is saying that the top most method of the exception is that method. It's very bizarre.

Any ideas of how I can track this down, or at least to properly catch the exception?


Solution

  • A FileLoadException is a pretty serious mishap. It is raised when the JIT compiler tries to compile the code that you run in your thread. A try/catch pair cannot catch this exception because it is raised before the code starts executing. In other words, it bombs before you enter the try block. Given that this is a thread, you can't stop your program from crashing to the desktop. The last gasp you have is AppDomain.UnhandledException, the e.ExceptionObject's InnerException property tells you what is really going wrong.

    This exception should otherwise always be easily fixable. It is a configuration issue, the JIT compiler finds an assembly that has the wrong version number or is an old version of the assembly, something like that. If you can't diagnose it from AppDomain.UnhandledException then the Fuslogvw.exe tool can show you how it is finding the wrong assembly. A full rebuild of your solution ought to be halfway to a fix.