I have written a C# Windows Forms application, not a service (it is only used when the user is logged in and has a graphical user interface) that has a background thread run
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Or any of the other reasons suitable for what you want to accomplish
if (e.CloseReason == CloseReason.WindowsShutDown)
{
//Stop your infinite loop
}
}
I think Capture console exit C# should also be usable in your scenario.
Apart from that, maybe it is sufficient to set up your thread as background thread?
Take a look at the Microsoft.Win32.SystemEvents.SessionEnding event.
You call that thread a "background thread" but does it have IsBackground = true;
?
The system will only stop a thread that does.