从不同的线程操作线程

从不同的线程操作线程

本文介绍了从不同的线程操作线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中的节目我有2个线程除了主线程。
当用户关闭我要终止从主线程的线程之一的形式。
我如何去这样做?请为我提供的代码,如果可能的。

In a program in c# I have 2 threads apart from the main thread.When the user closes the form I want to terminate one of the threads from the main thread.How do I go about doing so?. Please provide me with the code if possible.

推荐答案

请的的使用 Thread.Abort的所推荐的其他答案,到目前为止,除非你想你的程序处于未知状态(请参阅和的获得更多信息)。如果关闭窗体实际上应杀的应用程序,你的可能的好 - 但在这种情况下,我只使用后台线程反正,当所有前台线程已经终止,它会自动死去推荐

Please don't use Thread.Abort as recommended by the other answers so far, unless you want your program to be in an unknown state (see articles by Ian Griffiths and Chris Sells for more info). If closing the form should actually be killing the app, you're probably okay - but in that case I'd recommend just using background threads anyway, which will automatically die when all foreground threads have terminated.

从乔·达菲的:

有在线程中止始终是安全的两种情况:


  • 线程的主要目的是中止在CLR
    的AppDomain卸载推倒线程。 [...]

  • 同步线程中止是安全的,但前提是主叫方希望
    例外,从方法抛出。 [...]

主题的所有其他用途的中止是有疑问的最好。 [...]
在线程中止在理论上比其他线程终止
机制更加安全,他们仍然可以出现在不合适的时候,如果不小心使用导致
不稳定和腐败行为。

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.

(同步螺纹中止是当线程中止本身,而不是由另一个线程被中止。)

(Synchronous thread aborts are when the thread aborts itself, rather than being aborted by another thread.)

有关的曼妙的关机(而不用担心进入奇州)使用从形式定期设定,并从其他线程检查标志 - 以内存模型考虑(例如无论是制作旗挥发或每次测试或设置)使用锁。参见为例话题我文章。

For graceful shutdown (without risking getting into odd states) use a flag which is set periodically from the form and checked from the other threads - taking the memory model into account (e.g. either making the flag volatile or using a lock each time you test or set it). See my article on the topic for an example.

这篇关于从不同的线程操作线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!