I created a small wpf window application. The MainWindow
has a button that when pressed, a thread is created and begins to execute. Below is my code for xaml:
<Window x:Class="Tester.MainWindow"
...
Title="MainWindow" Height="150" Width="300" Closed="OnWindowclose">
<Grid>
<Button Content="Start" HorizontalAlignment="Left" Margin="42,47,0,0" VerticalAlignment="Top" Width="75" Click="Start_Click"/>
</Grid>
Here is what my .cs code looks like:
public partial class MainWindow : Window
{
private Thread t1;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowclose(object sender, EventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
private void Start_Click(object sender, RoutedEventArgs e)
{
move = true;
t1 = new System.Threading.Thread(KeepMoving);
t1.Start();
}
private void KeepMoving()
{
// my code
}
}
Now, my problem is when I close the MainWindow
using its close button. I can still see that the application hasn't stopped. I have tried a couple of things after reading some stackoverflow posts and created an event OnWindowClose
and called application shutdown. But that doesn't seem to work as expected.
I don't want to call Thread.Abort() as it throws an exception and forums suggest not to go for it. This post seems similar to what I am looking to achieve, but still I did not get how to use it to stop thread in close window.
I am fairly new to threads so I am not sure what can I can do to fix the issue. Any help would be appreciated.
Thanks.