本文介绍了C#子线程仍在工作,即使主线程退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰巧从msdn读取了Semaphore类示例,如下所示: https://msdn. microsoft.com/en-us/library/system.threading.semaphore%28v=vs.110%29.aspx

I happened to read Semaphore class sample as below from msdn:https://msdn.microsoft.com/en-us/library/system.threading.semaphore%28v=vs.110%29.aspx

这是一个控制台应用程序,但是让我感到困惑的是,子线程甚至可以在主线程退出时也可以工作.

It's a console app, however something confused me that child threads are able to work even main thread exits.

据我了解,当主线程/进程退出时,所有子线程都将终止,这就是为什么我们通常会在主线程停止之前发出信号并等待子线程完成.我是错误的还是由于引用而在.net中更改了行为?

From my understanding, when main thread/process exits, all child threads will be terminated, that's why usually we signal and wait child threads to finish before main thread stops.Am I wrong or the behaviour has been changed in .net due to reference?

推荐答案

如果希望子线程在父线程终止时中止,则必须将其设置为后台线程.

If you want the child thread to abort on the termination of the parent thread, it must be set as a Background thread.

t.IsBackground = true;
t.Start(i);

否则,所有前台线程都会在进程退出之前运行完毕

Otherwise, all foreground threads run to completion before the process exits

这篇关于C#子线程仍在工作,即使主线程退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:47