1

I want to run a long running opeartion in the background. The requirements are:

  1. The operation should run async to the calling thread.

  2. The calling thread can wait on the operation to complete and obtain its result

  3. Upon timeout, the operation should be aborted at once.

I would have used task, but there is no mechanism that I know of to kill the task dead cold. Cancel token is not suitable for me, I would only kill a task if it gets stuck for unknown reason - (a bug) , this is a fail-safe mechanism. Needles to say if the task is stuck, there is no use in requesting cancel. Same goes for BackgroundWorker.

Is there anything more elagent than using a shared object between the calling thread and a background thread?

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
omer schleifer
  • 3,897
  • 5
  • 31
  • 42
  • It sounds you likely need `Thread.Abort()` or something like that neither that is reliable when your thread is executing unmanaged code – Sriram Sakthivel Nov 11 '13 at 15:58
  • `ThreadAbortException` also has the problem that it by default, if caught, gets rethrown, so it needs extra work to allow the thread to be reused for other tasks. –  Nov 11 '13 at 16:00

2 Answers2

5

There is nothing more elegant than using a shared object, since using a shared object is the elegant way of doing this :)

You cant provide a generic way of killing a task safely: Since the killer thread does not have any clue of what the killee is doing when trying to kill it, this would potentially leave your object model in a "corrupted" state.

Thread.Abort() has been created to do that the cleanest way possible: By throwing an exception (which allows "finally" statements to dispose used resources, or running transactions disposal on killed thread). But this method can make the code throw an exception in unexpected location. It is highly not recommended.

nb: Thread.Abort() does not work in any case (example: wont work if your thread is running native code via a P/Invoke for instance)

Thus, the elegant solution is to write clean code, which can decide when it wants to be killed (via a cancellation token).

nb2: The ultimate "Thread.Abort()" which will work in any case, and which which will keep things isolated: Create a new AppDomain, run your killable code in this AppDomain (via remoting), and call AppDomain.Unload() when you want to stop everything.

This is a quite extreme solution, though.

Olivier
  • 5,578
  • 2
  • 31
  • 46
0

The only way to kill a thread 'dead cold' that I know of is Thread.Abort, however, you will see a lot of answers to this related question, Killing a Thread C#, indicating that it is generally bad practice to use it, except in rare occasions.

Another option is to avoid trying to kill the task dead cold and implement better error handling in your task such that it gracefully handles exceptions and situations where it 'gets stuck'.

Community
  • 1
  • 1
pixelTitan
  • 455
  • 3
  • 10