gpt4 book ai didi

c# - 从不同的线程操作线程

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

在 c# 程序中,除了主线程外,我还有 2 个线程。当用户关闭表单时,我想终止主线程中的一个线程。我该怎么做呢?如果可能,请向我提供代码。

最佳答案

不要按照目前其他答案的建议使用Thread.Abort,除非您希望您的程序处于未知状态(参见 Ian Griffiths 的文章和 Chris Sells 了解更多信息)。如果关闭表单实际上应该杀死应用程序,你可能没问题 - 但在那种情况下我建议无论如何都使用后台线程,当所有前台线程终止时它会自动死亡。

来自 Joe Duffy 的 "Concurrent Programming in Windows":

There are two situations in which thread aborts are always safe:

  • The main purpose of thread aborts is to tear down threads during CLR AppDomain unloads. [...]
  • Synchronous thread aborts are safe, provided that callers expect an exception to be thrown from the method. [...]

All other uses of thread aborts are questionable at best. [...] While thread aborts are theoretically safer than other thread termination mechanisms, they can still occur at inopportune times, leading to instability and corruption if used without care.

(同步线程中止是指线程自己中止,而不是被另一个线程中止。)

对于优雅关闭(没有进入奇怪状态的风险)使用一个标志,该标志从表单定期设置并从其他线程检查 - 考虑内存模型(例如,使标志volatile 或每次测试或设置时都使用锁)。有关示例,请参见我的 article on the topic

关于c# - 从不同的线程操作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771134/

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