.NET 线程和垃圾 Collection/Phantom 进程

.NET Threads and Garbage Collection/Phantom process

我目前正在尝试找出如何最好地 运行 .NET Core 2.x 应用程序作为 Windows 服务,特别是 运行 NServiceBus 端点对于消息系统。我的原始原型是从 Particular 的一些 Windows Service hosting docs 构建的。然后,我采用该功能原型并将其转换为 .NET Standard 库,供其他团队成员构建,但发现它对他们(或者我自己,如果我 2 周不看它的话)不是超级直观。

当然,在我构建了一个功能原型并将其部署到生产环境之后,我发现了一个更优雅的解决方案,它使用 .NET Core 的 GenericHostBuilder,由 Mr. Steve Gordon 提供。大多数代码对我来说都有意义,但我挂断了 new Thread(...).Start();,可能是因为我没有任何在 C# 和 .NET 中使用 Thread 的具体经验。

  1. new创建一个 Thread 并且保持不引用它感觉真的很不对。我担心这样做可能会导致内存泄漏,或者垃圾收集器会捡起它?我确实找到了 this SO 答案,这让我放心,即使我不持有对 Thread 的引用,CLR 也会。所以听起来不应该担心 GC 最终确定线程,对吗?
  2. 谁能给我解释一下为什么 Thread 没有调用 Abort()?是因为 CLR 管理线程并且知道在主线程关闭时停止其他线程吗?还是跟在IHostLifetime.StopAsync()方法中调用ServiceBase.Stop()方法有什么关系?

如果这些事情可以在某处 Thread 的某些文档中得到解释,我非常乐意获得 "RTFM" 并找到文档。目前我还没有找到任何可以给我明确解释的东西。

当线程执行完成并超出范围时,垃圾收集器最终会回收资源(当感觉需要时)。 Thread 也没有实现 IDisposable 所以你真的不需要用它来打扰自己(除非你在其中执行无限循环)

关于 Thread.AbortThread.Interrupt,我诚实的回答是你不应该使用这两种方法中的任何一种来终止线程。建议根本不要使用 Thread.AbortThread.Interrupt 方法 - 您应该利用同步对象(如 WaitHandles 或 Semaphores 等)并执行线程的正常终止您正在使用。

中智words of Eric Lippert(常驻CLR精灵)

In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.

一些补充阅读

  • Do we need to dispose or terminate a thread in C# after usage?

  • C# Thread object lifetime