1

I'm working on an application where the user can start a "task" that spawns on a separate thread.

The user is very likely to start this task and then restart it several times with slightly different parameters each time.

I could use Thread.Abort, or I could rewrite the code in the task so that there are numerous points where the task checks if the user wants to restart it.

Should Thread.Abort only be used in exceptional circumstances, or is it acceptable for this sort of thing?

Mr. Smith
  • 4,288
  • 7
  • 40
  • 82

1 Answers1

2

Checking at specific places in your code if the thread execution needs to stop would generally be preferable, because you have no control over where in the code execution stops using Thread.Abort. That could leave the application in some indeterminate (possibly invalid) state, depending on what the thread does. An added advantage is not having to deal with the ThreadAbortException. More explanation here.

However, from your question I understand that the only reason for aborting the thread would be to start it anew with different parameters. Instead, signal the thread that the parameters have changed, and reuse the same thread. Creating a new thread is a relatively expensive operation and can be avoided in your case.

Community
  • 1
  • 1
Thorarin
  • 47,289
  • 11
  • 75
  • 111