-1

I'm working for some AOI framework. In our case, all threads must stop immediatly when user click the emergency button. The thread's job is calling some heavy cpu loading in un-managed c++ dlls.

As far as i know, .net is not recommand to abort any thread or task. So is there any wait to kill the thread in un-managed dll?

  • 6
    Why not kill the process that hosts the thread? – ProgrammingLlama May 23 '22 at 06:11
  • 3
    There are ways to kill threads, but the same "not recommended" warning applies to all the ways you might possibly find. Forcibly killing a thread from outside of it should be reserved for when you're also tearing down the process, but even then it is questionable. Is there no way to redesign the code to have cooperative termination (you ask it to terminate, it terminates itself in an orderly fashion)? – Lasse V. Karlsen May 23 '22 at 07:30

1 Answers1

1

If killing jobs is crucial to the workflow, put each "killable" unit of work in a separate process, which you can then kill much more easily using Process.Kill().

Why? Because threads are relatively hard to manage, especially stop/kill them, especially when you don't control the code that runs on them.

Why is that? Because the ways to kill threads are:

  1. Cooperatively: Signal the thread to stop, then wait for the thread's code to see the signal and exit. That's how Task Canellation works. CON: If the code doesn't check for cancellation during long/block operations, the cancel will not happen. And if you don't control the code, you can't add that.
  2. Pre-emptively: Using Thread.Abort() or its unmanaged equivalent. There are many issues with it, see What's wrong with using Thread.Abort()
Jonathan
  • 6,939
  • 4
  • 44
  • 61
  • Also note that since .NET 5, attempting to call `Thread.Abort()` will result in a `PlatformNotSupportedException` – Matthew Watson May 23 '22 at 08:19
  • Thanks the reply. I will use the process method to avoid abort!! But it will have more cost on process communication? – young egg May 26 '22 at 05:29
  • @youngegg: Yes, processes are more costly than threads. This is true for unix/linux, and even more so on Windows. For inter-process communications, if you can use shared memory, the perf can be comparable to in-process. As always, you must measure to know the actual perf impact. – Jonathan May 26 '22 at 11:53