0

In my C# code there is a Main window which starts multiple threads.Some of these thread cause message boxes to show.When i close the main window I need all the threads i started to be aborted safely.I tried doing it by adding the threads to a list and then aborting them.But everytime ThreadAbort exception is thrown. Please suggest me a way to do this

Shaiju Janardhanan
  • 546
  • 1
  • 11
  • 21
  • Show the code you used when adding them to a list –  Dec 18 '13 at 09:49
  • Displaying message boxes from a thread solves one problem but creates three new ones. – Hans Passant Dec 18 '13 at 09:51
  • possible duplicate of [How to stop BackgroundWorker on Form's Closing event?](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event) – Hans Passant Dec 18 '13 at 09:51
  • Have you considered the design of your application? It sounds like you're having to resort to this because you feel you do not know how to do this in a safe/logical way. – Moo-Juice Dec 18 '13 at 10:25
  • @Moo-Juice I am actually using REST messages for communication in the thread.But sometimes the response takes too much time to receive.This keeps the thread alive for longer duration.Is there a way a better way to wait for the REST response? – Shaiju Janardhanan Dec 18 '13 at 10:45
  • @ShaijuJanardhanan, have a look at doing it asynchronously so that your main UI thread isn't blocked. – Moo-Juice Dec 18 '13 at 10:50

1 Answers1

2

The very purpose of Thread.Abort is raising a ThreadAbortException. This kills the thread.

From MSDN:

Thread.Abort Method

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.

Using Thread.Abort will not terminate the thread in a clean way. The usual safe solution for stopping a thread is creating a volatile bool stop flag on that thread, which your thread checks from time to time to know whether it should stop.

user703016
  • 37,307
  • 8
  • 87
  • 112