0

I'm developing some WPF program and make a thread called 'thCheckIdle' in 'SyringeTricontinent.cs' class which is generated in 'MainWindow.xaml.cs'. I wanna kill this thread when program exits so I added exit event in Application class and make behind code below:

    private void Application_Exit(object sender, ExitEventArgs e)
    {
        if(((MainWindow)System.Windows.Application.Current.MainWindow).syringe.thCheckIdle!= null)
        {
            ((MainWindow)System.Windows.Application.Current.MainWindow).syringe.thCheckIdle.Abort();
        }    
    }

But it doesn't work popping up "An unhandled exception of type 'System.NullReferenceException' occurred in WHALE.exe" message and I figure out that status of MainWindow is null even program is executed showing MainWindow.

How can I kill that thread when I exit the main program?

KimSJ
  • 113
  • 3
  • `Thread.Abort()` is a horrible way to stop a thread. Depending on what your threads are doing, it might make sense to set the thread to background. If you use `Task.Run()` to start the code, then the thread assigned to the task will be a background thread already, but that wouldn't be an appropriate solution for a long-running thread that does idle checks. Debugging `NullReferenceException` is a whole other duplicate. If you get to a point where you've exhausted all the useful advice in that duplicate and still need help, you need to post a question with a [mcve] that reproduces the problem. – Peter Duniho Jan 17 '18 at 02:53

1 Answers1

1

You can make it a Background Thread so that it doesn't stop your app from exiting when the main thread is done. Just say thCheckIdle.IsBackground = true; when creating it.

https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isbackground?view=netframework-4.7.1

Furkan Kambay
  • 692
  • 1
  • 7
  • 18
  • Thanks a lot. It clearly works without Application exit event. But i still wonder how to access MainWindows' field in Application class. It works other child windows or classes generated in MainWindow using "((MainWindow)System.Windows.Application.Current.MainWindow)" but just not works in Application class. – KimSJ Jan 17 '18 at 02:54
  • @KimSJ You can subscribe to the Application's `Activated` event and access the current MainWindow from there. – Aniruddha Varma Jan 17 '18 at 04:54