2

Possible Duplicate:
Killing a thread (C#)

I have a program that when started will spawn off a thread, the threads main process execute a few method calls that are rather meaty.

The parent class that spawned the thread needs to be able to set the thread as aborted (or stopped), and the thread needs to gracefully stop and clean up/revert changes it's made.

Is there a nice way to abort/stop a thread other than setting a volatile bool and checking if it has been set in the spawned off thread's process? The thread's process calls many methods and could take hours so checking in every single method call is a bit tedious.

I am not stuck to any particular Threading implementation so am up for suggestions

Community
  • 1
  • 1
adamwtiko
  • 2,865
  • 8
  • 39
  • 47
  • 2
    Please avoid the word 'abort' here. Your approach is OK and nice. Thread.Abort() is dangerous. – H H Apr 20 '11 at 14:06

1 Answers1

4

If you're using the TPL in .NET 4 or a back-ported version of it for .NET 3.5 available with Rx Extensions, you can use the cooperative cancellation system, which improves on the classic boolean flag system to handle boundary cases, such as cancelling multiple parallel tasks, allowing continuation logic in the case of cancellation and, as the framework evolves, enabling forward support for new BCL functionality that natively supports the new cancellation model. It also decouples the canceller from the task being cancelled, so that you can control which code is given cancellation permissions.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102