gpt4 book ai didi

c# - 如何检测主线程何时终止?

转载 作者:行者123 更新时间:2023-11-30 13:42:58 25 4
gpt4 key购买 nike

我需要知道的:

我想检测主线程(进程?)何时终止,以便我可以确保在终止之前执行某些操作。

我自己的发现:

我找到了事件 AppDomain.DomainUnloadAppDomain.ProcessExitAppDomain.DomainUnload 似乎适用于 MbUnit 等非应用程序。 AppDomain.ProcessExit 似乎适用于应用程序,但有 3 秒的时间限制,我真的不喜欢。是否有更多方法来检测 AppDomain/进程何时终止?

背景:

我正在寻找这样的事件,以确保我的日志在应用程序终止时持久保存到文件中。实际的日志记录在使用生产者-消费者模式的另一个线程上运行,日志条目很可能在内存中排队,我需要确保在应用程序终止时将这个队列保存到文件中。

还有什么我应该注意的吗?

更新:

更改以上内容以反射(reflect)我自己的发现。我对 ProcessExit 期间的 3 秒时间限制不满意。 MSDN 文档确实说它可以扩展:

The total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is three seconds, which can be overridden by an unmanaged host.

有谁知道如何覆盖默认值?

更多想法也非常感谢!

跟进:

I have posted a follow up question to this .

最佳答案

您的应用程序应该有一个入口点。通常你可以在所有任务终止时做一些日志记录:

static void Main()
{
try
{
Application.Run( .... );
}
finally
{
// logging ...
}
}

关于c# - 如何检测主线程何时终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1368697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com