Question

I have a .NET application which calls unmanaged method periodically in separate thread (every 5 seconds). And this method crashes sometimes. I need to process this situation somehow. The main problem is I cannot change c++ unmanaged code.

I tried different ways to handle this exception, but without any success:

  1. usual

    try {} catch (Exception ex) {}

and

try {} catch {}

2
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

3 System.Windows.Threading.Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_UnhandledException;

4. Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

In any case it just crashes silently.

Logically this thread should be restarted, but I know that Thread.Abort() is a bad practice. What is the best practice for such situations?

Thanks in advance.

Was it helpful?

Solution

If unmanaged code crashes your process, you're out of luck. There is no exception propagated to managed code. The only way to be stable against such a crash is to start the unmanaged code in a wholy separate process, not just a thread. You can than use inter-process communication to exchange data as needed, and restart the process if it crashes.

Also, Thread.Abort is not only a bad practice - it also will not help you at all while the thread is inside the unmanaged code, such as when the unmanaged code "hangs". Thread.Abort will only be allowed to abort the thread as it exits back to managed code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top