2016-05-31 98 views
-1

对不起,问这个很愚蠢的问题,但我让这个程序测试是否所有前景线程都等待在程序终止前完成。.NET应用程序在终止程序之前是否等待所有前景线程完成?

但是在这个程序中,只要我点击任何键退出程序,主线程就会终止,然后关闭应用程序,即使在执行其他前台线程的过程中也是如此。

using System; 
using System.Threading; 

namespace ForegroundThreads 
{ 
    // This is a program to test whether or not the application 
    // will terminate when there is a pending foreground thread running. 

    // In describing the difference between foreground and background threads, 
    // the documentation states that an application will terminate all 
    // background threads when all foreground threads have finished execution. 
    // This implies that the application will stall the main thread until 
    // all foreground threads have completed execution. Let us see if this 
    // is the case. 

    // Quote: 
    // A managed thread is either a background thread or a foreground thread. 
    // Background threads are identical to foreground threads with one exception: 
    // a background thread does not keep the managed execution environment running. 
    // Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), 
    // the system stops all background threads and shuts down. 
    // Source: https://msdn.microsoft.com/en-us/library/h339syd0%28v=vs.110%29.aspx 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var t = new Thread(() => { 1000000.Times(() => { Console.WriteLine("Hello"); }); }); 
      t.Start(); 

      Console.WriteLine("Press any key to exit the main thread..."); 
      Console.ReadKey(); 
     } 
    } 

    public static class Extensions 
    { 
     public static void Times(this int numTimes, Action action) 
     { 
      for (int i = 0; i < numTimes; i++, action()) ; 
     } 
    } 
} 

我注意到,当我运行此代码

在我的机器,如果我减少次数,以较小的值,比如,1000行为,它会立即杀死所有前台线程时主线程退出。但是,如果我将值设得很大,例如100万,那么系统会继续运行我创建的前台线程,忽略所有击键,直到完成一百万次打印。

更新

GSerg挂钩,要求同样的事情,另外一个问题。但是,如果你仔细阅读这个问题,那个问题的海报真的在问:“发生了什么事?”

答案只是引用MSDN解释所有前台线程正在等待。我的问题是争论的。

我的问题是 - 为什么程序等待前景线程有时完成,而在其他时间没有。因此,在另一个问题中的答案对我没有任何帮助。

+0

我无法复制。如果我将线程保持为前景,当按Enter键时程序不会终止。如果我将其IsBackground属性设置为true,程序会终止。 –

+0

尝试更改'Times'方法的接收者的值。我正在更新这个问题,并提供更多的细节,以便它等待前景线程完成,以及何时不完成。在我的机器上,如果我将次数减少到一个较小的值,例如1000,它会在主线程退出时立即杀死所有前台线程。但是,如果我将值设得很大,例如100万,那么系统会继续运行我创建的前台线程,忽略所有击键,直到完成一百万次打印。 –

+0

使用Thread.Sleep()而不是Console.Writeline()可能更可靠。 –

回答

0

我的不好,我的眼睛没有看到20-20。该程序确实等待派生的前景线程完成执行。

发生了什么事是,当我通过降低Times方法的整数接收机的价值,即使这个程序实际上已经完成打印减少迭代次数所有你好的,它似乎我的眼睛该程序仍在忙于打印。这导致我相信产生的线程仍在运行,当我按下键盘上的任何其他键时,它立即终止该过程。

相关问题