繁体   English   中英

如果后台线程中有未处理的异常,如何使主进程崩溃

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

我有一个发布者,调度员,订阅者。

发布者通过调度程序向订阅者发布事件。

订户是嵌入在S.exe中的com对象,当特定事件来自Publisher.exe时可以从dispatcher.exe进行回调。

我希望订户内的任何异常都将终止S.exe。

我做了调查:

  1. 具有配置的任务可以终止主进程。 相关文章https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.taskscheduler.unobservedtaskexception?view=netframework-4.7.2

  2. 在我的代码中新建一个线程,没有任何特定的配置也可以,线程内部任何未处理的异常都可能使主进程崩溃。 相关文章, https://docs.microsoft.com/zh-cn/dotnet/standard/threading/exceptions-in-managed-threads

一个线程的两个属性:{isbackground,isThreadPoolThread}。

  1. 任务是{true,true}
  2. 人工线程为{true,false},
  3. 订户回调线程为{true,false}。

是否还有其他配置(例如)可以设置为控制是否使主进程崩溃?

您可以处理AppDomain.CurrentDomain.UnhandledException事件,在该事件中,您可以使用Process.GetCurrentProcess()获取当前进程并杀死该进程,以便您的exe终止。

将此行Main()放在Program.cs

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException

然后,如下所示实现CurrentDomain_UnhandledException

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

根据您的问题陈述,这只是概念。 您可以根据需要进行更改。

RCW将COM内的任何异常包装为HRESULT返回给其客户端。 因此,当在COM线程中引发异常时,无法使主进程崩溃。

答案可能与以下有关: COM方法通过返回HRESULT报告错误; .NET方法通过抛出异常来报告它们。 运行时处理两者之间的过渡。 .NET Framework中的每个异常类都映射到一个HRESULT。

来自https://docs.microsoft.com/zh-cn/dotnet/framework/interop/how-to-map-hresults-and-exceptions

和其他有用的链接: https : //docs.microsoft.com/zh-cn/dotnet/framework/interop/runtime-callable-wrapper

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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