Today I got a Problem with a Deadlock in a App I developed. In particular I am stopping a Window which started a Thread in the Background.
Problem? On Closing of the Window the Window closed, but the Process was still alive in the Background. I thought about if the Thread itself blocks, but as a Background-declared Thread it should normaly shut down anyway. But then I noticed that "Logic.DoSomething()" started it's own endless-Threads without declaring it as Background-Threads.
So why is a (non-Background) Thread in a (Background) Thread blocking the Process? Shouldn't it shutdown because it's "Parent" runs as Background-Thread? And if not, why doesn't block the Parent-Thread itself?
public partial class MainWindow : Window
{
private Thread TheThread { get; set; }
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
Closed += MainWindow_Closed;
}
private void MainWindow_Loaded(object sender, EventArgs e)
{
// Create the (background-)thread and start it
TheThread = new Thread(() => Logic.DoSomething());
TheThread.IsBackground = true;
TheThread.Start();
}
private void MainWindow_Closed(object sender, EventArgs e)
{
// Close Thread if existent.
TheThread.Abort("Window was closed");
TheThread.Join(500);
}
}
PS: Please note, that I don't use a Worker-Object because I handle the Abort-Exception in the Thread normaly.
Edit: It is a theoretical Question for a Windows Presentation Foundation-Project (WPF) and not for an Windows Forms Project. Besides of that the Basic-Question was NOT how to Start and Stop a Thread using e.g. CancellationToken. It was a Question why a Thread made by a Process doesn't kill the Process it called or is gettin stuck in the Join. Hope this is clear enough.