5

I need to terminate a frozen thread, I set IsBackground as true but it stays alive. Thread's properties:

ThreadState = AbortRequested

IsBackground = true

When I examine the frozen spot I find the line below:

resultDetect = Detect(input, ref output);

The spot is a 3rd party code (Method Detect). The thread only updates resultDetect as you see. I need to abort that thread and re-start a new one to continue. Otherwise, the application waits and does nothing -fresh resultDetect needed-

How can I kill the thread that doesn't die?

Community
  • 1
  • 1
Nime Cloud
  • 6,162
  • 14
  • 43
  • 75

3 Answers3

4

There's only one way to safely kill a hung thread in your application: Environment.Exit And even that can fail if the thread is running kernel code.

It's best not to use third-party code that hangs. If you have no choice, then run it in a separate process.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • This is already server-side of the code. Method scans a large amount of data (~1GB RAM). How can I start a new process in super fast way? Say I will split server-side into base/memory section and scan section... So I can kill scan section. I think I'm gonna ask a new question. – Nime Cloud Jul 25 '11 at 13:07
  • 1
    @Nime: There's not nearly enough detail there to go on, but I will mention that the [`MemoryMappedFile`](http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.aspx) class allows sharing memory between processes, so this is a fast way to give the scan process read-only access to a chuck of data while still being able to kill it independently of the main process. – Ben Voigt Jul 25 '11 at 13:10
2

If Detect transitions into unmanaged code then the CLR will defer the injection of the ThreadAbortException until it returns. This behavior changed in .NET 2.0 to make thread aborts a lot safer. The CLR is trying really hard to protect you from corrupting the state of the process which would be very likely in the case of unmanaged code since you do not get the benefit of the isolation of app domains which can be easily unloaded under an all managed scenario. Really, the only solution is to run this API in a separate process and use WCF, remoting, etc. to communicate with it.

Brian Gideon
  • 47,849
  • 13
  • 107
  • 150
1

Maybe try to call Thread.Abort(). Although it is not recommended (See Killing a .NET thread)

Community
  • 1
  • 1
marc
  • 6,103
  • 1
  • 28
  • 33