This problem is rather complicated and I'm not sure about how to tackle it. I get the following exception when I start my application.
[FATAL] Unhandled exception. EXCEPTION OCCURRED:System.Runtime.InteropServices.SEHException External component has thrown an exception. Boolean CloseHandle(IntPtr)
[FATAL] Last Win32 error code: 00000006; Last HRESULT: 80070006
This only occurs when I run the debugger. If I start the application without a debugger, then it never throws an SEHException. As another fact, when I continue it does pop up again in Visual Studio and then exits the application.
I have now managed to narrow it down to this:
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
InternalDispatcher = new WpfDispatcher(dispatcher);
It does occur right after the constructor call of WpfDispatcher.
internal WpfDispatcher([NotNull] Dispatcher dispatcher)
{
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
}
I don't see why this happens, though. The WpfDispatcher-class is only a wrapper which allows me to use either WinForm or WPF to dispatch, depending on the selected compatibility mode.
And why is this only happening with an attached debugger? The code exists for a long time already and this started to happen only recently...
Is there any way to narrow it down? I just don't get why this happens.
PS: Just checked the threads when this happens and it seems like this exception originates from the GC Finalizer Thread:
Not Flagged > 4628 2 Worker Thread GC Finalizer Thread mscorlib.dll!Microsoft.Win32.SafeHandles.SafeFileHandle.ReleaseHandle Highest
PS2: Activating the native debugger, I get this (slightly) more detailed exception:
Exception thrown at 0xFE58917A in Lab.Wpf.exe: 0xC0000008: An invalid handle was specified.
Related
Normally, when the debugger is attached, Visual Studio 2010 stops at an unhandled exception even if the Exceptions dialog doesn’t have the tickmark for the exception type in the “Thrown” column. The keyword here is unhandled; said dialog refers only to handled exceptions.
However, in the following minimal example, Visual Studio 2010 does not stop at the exception for me, even though it appears in the Immediate Window as a first-chance exception:
EDIT: The first minimal example I posted was fixed by the first answer I received, but unfortunately the following example still exhibits the problem:
using System;
using System.Net.Sockets;
namespace SocketTest
{
class Program
{
static void Main(string[] args)
{
var listener = new TcpListener(8080);
listener.Start();
AsyncCallback accepter = null;
accepter = ar =>
{
var socket = listener.EndAcceptSocket(ar);
var buffer = new byte[65536];
AsyncCallback receiver = null;
receiver = ar2 =>
{
var bytesRead = socket.EndReceive(ar2);
throw new InvalidOperationException();
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, receiver, null);
};
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, receiver, null);
listener.BeginAcceptSocket(accepter, null);
};
listener.BeginAcceptSocket(accepter, null);
Console.WriteLine("Feel free to connect to port 8080 now.");
Console.ReadLine();
}
}
}
If you run this, connect to it by running telnet localhost 8080 and then type any character into telnet, hopefully you will see what I see: the program just aborts silently.
Why does Visual Studio apparently swallow this exception? Can I get it to break at the exception as it usually does?
(Interestingly, throwing inside the BeginAcceptSocket callback does get caught, as does an exception in a normal thread started with Thread.Start. I can only reproduce the issue by throwing inside the BeginReceive callback.)
This is a known bug in CLR version 4. The feedback article is here. A possible workaround is to change the framework target to version 3.5. I'll just quote the relevant portion of the feedback response:
We have investigated the issue and determined there is a bug in CLR
v4.0 which causes this. The process does throw the exception (you can
catch it with a catch handler for example) but the debugger was not
properly notified of the unhandled exception. This causes the process
to appear to exit without any indication from the debugger about what
happened. We have investigated potential fixes, however all of the
fixes had moderate risk of breaking other functionality. Because it
was very late in product cycle we decided it was safer not to fix this
issue and risk creating new bugs. We will continue to track this issue
as part of our next release cycle.
The issue is restricted to exceptions that escape managed code where
the thread was created using a few specific API calls:
new
System.Threading.Timer()
ThreadPool.UnsafeQueueNativeOverloapped
ThreadPool.BindHandle
ThreadPool.RegisterWaitForSingleObject.
It is RegisterWaitForSingleObject() in this specific case.
Since you see only a 'Thrown' checkbox in the exception settings, my suspicion is that you have '.Net Framework Source Stepping' enabled in your debug settings. If you enable 'Just My Code' (which disables '.Net Framework Source Stepping'), you should get 'User-Unhandled' and 'Thrown' checkboxes in your exception settings dialog and you will also catch the exception in the debugger.
Screen Shot O' Victory:
This is what I have discovered so far:
If no exceptions are explicitly checked in the Debug->Exceptions dialog and Options->Debugging->"Enable Just My Code" (EJMC) is not checked, then an exception thrown in any of the callbacks will not break with First Chance Exception (FCE)
If no exceptions are explicitly checked in the Debug->Exceptions dialog and EJMC is checked, then an exception thrown in the TCPListener's callback will break with FCE, but will not break with FCE in the Socket's callback
a. An exception thrown will not break with FCE in the Socket's callback, even if the TCPListener's blocking AcceptSocket() is called (so no callback for listener).
If System.InvalidOperationException (or System) is checked in Debug->Exceptions, then an appropriate exception thrown in any of the callbacks will break with FCE, regardless of whether EJMC is checked or not.
The above is true whether the callbacks are specified as lambda or in an excplicit user function
I do not know why VS does not break with FCE in the socket callback if the exception is not excplicitly checked in Debug->Exceptions (what makes the socket callback different from the listener callback).
I have a delegate which is attached to an event in the Excel interop component. The goal is to update a winforms control with updated info from Excel. Since I'm changing Control properties I need to use Invoke:
public delegate void DataGridViewUpdate(object[,] data);
...
excel.InteractiveEdit( delegate(object[,] data) {
Invoke(new Common.DataGridViewUpdate(back_from_excel), new object[] { data });
});
...
private void back_from_excel(object[,] data) {
// datagridview updating code
// an exception is thrown here !
}
(This code is in the Form class that I'm updating so it's Invoking on this)
Basically my problem is that when an exception occurs in the back_from_excel(object[,] data) method, the debugger doesn't catch it. I know the delegate is running in the correct UI thread because I have no problems manipulating form controls.
Specifically what happens is that when back_from_excel hits an unhandled exception, it stops executing at that point. The rest of the application continues running and is responsive. The debugger doesn't pause. The output pane shows:
A first chance exception of type 'System.NullReferenceException' occurred in My Application.exe
A first chance exception of type 'System.NullReferenceException' occurred in System.Windows.Forms.dll
It doesn't give me any hints about which line caused the problem, just that it's somewhere in the .exe.
My question is: am I doing the Invoke thing right? It seems kind of strange to have delegate - Invoke - delegate chained together like that, but I do need to pass a delegate that Invokes a delegate. Is my problem in Visual Studio rather than in C#? If so how do I get the debugger re-attached to that UI thread?
A "first chance exception" indicates that an exception was thrown, but that it was caught at some point. Since you're passing a delegate to the InteractiveEdit method, that method can easily swallow any exceptions produced by the delegate.
By default, Visual Studio will only catch exceptions that don't get caught. If you want to catch all exceptions, regardless of whether they are caught, you need to configure Visual Studio to break on all exceptions. See this link for details on how to do this.
C#, using VS2010 and I've got something that makes no sense.
At startup my program needs to load several hundred k from text files. After ensuring the loading code was working fine I threw it in a background thread. So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't. This of course goes boom.
The trigger code:
BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();
and the stuff that's going boom is in DatabaseLoaded().
I put some messageboxes to trace what's going on: The first and last lines of the Load() method and the first line of DatabaseLoaded().
In the IDE this triggers as I expect: Load() beginning, Load() done, DatabaseLoaded(). However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)
Am I nuts or is Microsoft?
RunWorkerCompleted will be invoked in case of an error (such as an unhandled exception in Database.Load()). Check the Error property of the RunWorkerCompletedEventArgs.
There's probably an exception thrown from Database.Load(). BackgroundWorker catches any unhandled exception before triggering the RunWorkerCompleted event. Check the RunWorkerCompletedEventArgs.Error property in DatabaseLoaded.
Take this code:
using System;
namespace OddThrow
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception("Exception!");
}
finally
{
System.Threading.Thread.Sleep(2500);
Console.Error.WriteLine("I'm dying!");
System.Threading.Thread.Sleep(2500);
}
}
}
}
Which gives me this output:
Unhandled Exception: System.Exception: Exception!
at OddThrow.Program.Main(String[] args) in C:\Documents and Settings\username
\My Documents\Visual Studio 2008\Projects\OddThrow\OddThrow\Program.cs:line 14
I'm dying!
My question is: why does the unhandled exception text occur before the finally's? In my mind, the finally should be excuted as the stack unwinds, before we even know that this exception is unhandled. Note the calls to Sleep() - these occur after the unhandled exception is printed, as if it was doing this following:
Unhandled exception text/message
Finally blocks.
Terminate application
According to the C# standard, §8.9.5, this behaviour is wrong:
In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (§8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
If an exception handler was not located in the current function member invocation, the function member invocation is terminated. The steps above are then repeated for the caller of the function member with a throw point corresponding to the statement from which the function member was invoked.
If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.
Where am I going wrong? (I've got some custom console error messages, and this is in-the-way. Minor, just annoying, and making me question the language...)
The standard's statements about the order of execution are correct, and not inconsistent with what you are observing. The "Unhandled exception" message is allowed to appear at any point in the process, because it is just a message from the CLR, not actually an exception handler itself. The rules about order of execution only apply to code being executed inside the CLR, not to what the CLR itself does.
What you've actually done is expose an implementation detail, which is that unhandled exceptions are recognised by looking at a stack of which try{} blocks we are inside, rather than by actually exploring all the way to the root. Exceptions may or may not be handled by looking at this stack, but unhandled exceptions are recognised this way.
As you may be aware, if you put a top-level try{}catch{} in your main function, then you will see the behaviour you expect: each function's finally will be executed before checking the next frame up for a matching catch{}.
I could be way off base in the way I'm reading things...but you have a try finally block without a catch.
Juding by the description you posted, since the Exception is never caught, it bubbles up to the caller, works it's way up through the stack, is eventually unhandled, the call terminates, and then the finally block is called.
The output is actually from the default CLR exception handler. Exception Handlers occur before the finally block. After the finally block the CLR terminates because of the unhandled exception (it can't terminate before, as c# guarantees [1] that the finally clause is called).
So I'd say it's just standard behaviour, exception handling occurs before finally.
[1] guranteed during normal operation at least in absence of internal runtime errors or power outage
To add more into the mix, consider this:
using System;
namespace OddThrow
{
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
delegate(object sender, UnhandledExceptionEventArgs e)
{
Console.Out.WriteLine("In AppDomain.UnhandledException");
};
try
{
throw new Exception("Exception!");
}
catch
{
Console.Error.WriteLine("In catch");
throw;
}
finally
{
Console.Error.WriteLine("In finally");
}
}
}
}
Which on my system (Norwegian) shows this:
[C:\..] ConsoleApplication5.exe
In catch
In AppDomain.UnhandledException
Ubehandlet unntak: System.Exception: Exception!
ved OddThrow.Program.Main() i ..\Program.cs:linje 24
In finally
Although not completely expected, the program does behave as it should. A finally block is not expected to be run first, it is only expected to be run always.
I adjusted your sample:
public static void Main()
{
try
{
Console.WriteLine("Before throwing");
throw new Exception("Exception!");
}
finally
{
Console.WriteLine("In finally");
Console.ReadLine();
}
}
In this case you will get the nasty unhandled exception dialog, but afterwards the console will output and wait for input, thus executing the finally, just not before windows itself catches the unhandled exception.
A try/finally without a catch will use the default handler which does exactly what you see. I use it all the time, e.g., in cases where handling the exception would be covering an error but there's still some cleanup you want to do.
Also remember that output to standard error and standard out are buffered.
The try-catch-finally blocks are working exactly as you expected if they are caught at some point. When I wrote a test program for this, and I use various nesting levels, the only case that it behaved in a way that matched what you described was when the exception was completely unhandled by code, and it bubbled out to the operating system.
Each time I ran it, the OS was what created the error message.
So the issue is not with C#, it is with the fact that an error that is unhandled by user code is no longer under the control of the application and therefore the runtime (I believe) cannot force an execution pattern on it.
If you had created a windows form application, and wrote all your messages to a textbox (then immediately flushing them) instead of writing directly to the console, you would not have seen that error message at all, because it was inserted into the error console by the calling application and not by your own code.
EDIT
I'll try to highlight the key part of that. Unhandled exceptions are out of your control, and you cannot determine when their exception handler will be executed. If you catch the exception at some point in your application, then the finally blocks will be executed before the lower-in-the-stack catch block.
To put a couple of answers together, what happens is that as soon as you have a Unhandled Exception a UnhandledExceptionEvent is raised on the AppDomain, then the code continues to execute (i.e. the finally). This is the MSDN Article on the event
Next try:
I believe this case isn't mentioned in the c# standard and I agree it seems to almost contradict it.
I believe the internal reason why this is happening is somewhat like this:
The CLR registers its default exception handler as SEH handler into FS:[0]
when you have more catches in your code, those handlers are added to the SEH chain. Alternatively, only the CLR handler is called during SEH handling and handles the CLR exception chain internally, I don't know which.
In your code when the exception is thrown, only the default handler is in the SEH chain. This handler is called before any stack unrolling begins.
The default exception handler knows that there are no exception handler registered on the stack. Therefore it calls all registered UnhandledException handler first, then prints its error message and marks the AppDomain for unloading.
Only after that stack unrolling even begins and finally blocks are called according the c# standard.
As i see it, the way the CLR handles unhandled exception isn't considered in the c# standard, only the order in which finallys are called during stack unrolling. This order is preserved. After that the "The impact of such termination is implementation-defined." clause takes effect.
I have a dialog that has to process large quantaties of data (the procedure is quite time consuming - first the ODBC fill takes its time, then the data processing kicks in) and the result is that the Form becomes unresponsive. This is not a problem really, it is enough to just open a "loading screen" in a new thread to notify the user of the process.
Recently I have discovered, that sometimes (it appears to be random) the new thread will throw an unhandled ThreadAbortException causing a crash report dialog box to show up (or JIT).
I do not understand why this exception would be thrown, or why it would be unhandled. Has anyone dealt with this before, or can anyone point me towards the probable cause of this behaviour?
Thank you!
EDIT: In case it matters, I open the loading screen like this:
//start of work load
Thread th = new Thread(new ThreadStart(MakeStep));
th.Start();
...
//end of work or error occurance:
th.Abort();
//
You're calling th.Abort() which injects a ThreadAbortException on the thread th. If that thread doesn't handle the exception it will be reported as an unhandled exception.
It is generally not recommended to abort other threads in this way, as you have no idea if the thread will handle an abort gracefully. A better solution is to use signaling between your threads.
ThreadAbortExceptions are raised when you call Thread.Abort(). Looks like you or a lib you are using is trying to kill your Thread.
If you don't know why it's aborting, better to let it go than to swallow the exception.
That being said, you need to wrap your MakeStep method in a try/catch and log the exception (and, of course, any innter exceptions). Something like this...
public void MakeStep()
{
try
{
InnerMakeStep(); // may throw TAE or some other exception
}catch(Exception e)
{
// log here k
throw; // in case it isn't a TAE
}
}
With the exception logged, the issue can be debugged. Right now, it could be a thousand things.