exit application after aborting thread
Hi there.
During my application a thread is started by the user. however when the user closes the app from the X button at the top right hand corner of the form, the application (or form) closes but app still remains in memory running
how can i kill the thread and remove the application from memory, as it should do normally when you run and close an application (like MS word etc...)
I have put this in my closing event handler of the form but doesnt seem to remove it from memory:
| |
private void frmMain_Closing(object sender, CancelEventArgs e){ i f (this.listenToClientThread !=null) { if (this.listenToClientThread.IsAlive) {this.listenToClientThread.Abort(System.Threading.ThreadState.Running); Application.Exit(); }}
|
it seems to have worked! Thank-you :)
when the thread is aborted, I would like to continue doing the rest of my code however it doesnt seem to because it aborts the thread and thats it...
The thread is a seperate thread (new thread) and runs a method in that thread. When the user presses stop for example, the thread is aborted (checking to see that the isbackground is true) ... but doesnt continue to do the rest of the code:
| |
if (restartService) { if (this.listenToClientThread.IsBackground | this.listenToClientThread.IsAlive) { this.listenToClientThread.Abort(System.Threading.ThreadState.Background); //Stops here, does not continue on to do the rest: this.listenToClientThread.IsBackground = false; this.listenToClientThread = null; this.StartServerService(); } else { this.StartServerService(); } } |
Are you running the "Abort" method in the same thread that you're trying to terminate? If so, that would explain why the rest of the code is not being run (cuz you just killed your running thread).
The correct way to abort a thread from within itself would be to just return. Also, you don't need to set the "IsBackground" property to false while aborting.