简体   繁体   中英

how to crash the main process if there is unhandled exception inside background thread

I have a publisher, dispatcher, subscriber.

publisher publish event through dispatcher to subscriber.

subscriber is a com object embedded in S.exe can be callback from dispatcher.exe when specific event coming from publisher.exe.

I expect any exception inside the subscriber to terminate the S.exe.

I did my investigation:

  1. task, with configuration can terminate the main process. related article, https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.unobservedtaskexception?view=netframework-4.7.2

  2. new a thread in my code, without any specific configuration can also, any unhandled exception inside the thread can crash the main process. related article, https://docs.microsoft.com/en-us/dotnet/standard/threading/exceptions-in-managed-threads

two attributes of one thread: {isbackground, isThreadPoolThread}.

  1. task is {true, true}
  2. artificial thread is {true, false},
  3. subscriber callback thread is {true, false}.

is there any other configuration, like , can set to control whether or not to crash the main process?

You can handle AppDomain.CurrentDomain.UnhandledException event in which you can get the current process by using Process.GetCurrentProcess() and kill that process so your exe will terminate.

Put this line Main() in Program.cs :

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException

Then implement CurrentDomain_UnhandledException as below.

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    var currentProcess = Process.GetCurrentProcess();
    currentProcess.Kill();
}

This is just concept as per your problem statement. You can change it as per your need.

Any exception inside a COM was wrapped as a HRESULT return to it's client by RCW. So, no way to crash the main process when the exception was thrown inside a COM thread.

The answer may be related with: COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.

from https://docs.microsoft.com/en-us/dotnet/framework/interop/how-to-map-hresults-and-exceptions

and other helpful links: https://docs.microsoft.com/en-us/dotnet/framework/interop/runtime-callable-wrapper

https://docs.microsoft.com/en-us/dotnet/framework/interop/com-callable-wrapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM