Sorry for asking this rather silly question but I made this program to test whether or not all foreground threads are awaited for their completion before the program terminates.
But in this program, as soon as I hit any key to exit the program, the main thread terminates and then closes the application even while in the middle of executing the other foreground thread.
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()) ;
}
}
}
The Behavior I Notice When I Run This Code
On my machine, if I reduce the number of times to a smaller value, say, 1000, it immediately kills all foreground threads when the main thread exits. But if I make the value large, like one million, for instance, the system keeps running that foreground thread I created disregarding all keystrokes until it has finished printing one million times.
Update
GSerg linked to another question that asks the same thing. However, if you read that question closely, the poster of that question is really asking, "What's going on?"
The answer simply quotes the MSDN explaining that all foreground threads are awaited for. My question contends the very thing.
My question is -- why is it that the program waits for the foreground thread to finish sometimes and it doesn't at other times. Hence, that answer in that other question is of no help to me.