Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

How to kill a managed tread that is hung inside unmanaged code during a P/Invoke call?

Back to Forum: Tech Off
  • User profile image

    This is somewhat related to this thread, but a different question.

    If I P/Invoke into unmanaged code and it gets hung, how can I kill the thread? This will obviously need to happen from a different thread. However, Thread.Abort does not work because the documentation states that the thread will only throw the ThreadAbortException once it returns from unmanaged code.

    So far the only way that I found to kill a hung thread is to kill the whole process via Process.Kill. But that is way overkill for what I want, and I am hoping there is a better way that allows me to kill just the thread itself.

    Any ideas?

  • User profile image

    The best idea: don't. Killing a thread is really never a good idea. This can leave the entire process in a broken state. Handles won't be closed properly. Locks won't be relinquished. Memory will leak. Shared state may be corrupt. And on and on and... boom.

    If you insist on doing this, you'll probably have to resort to P/Invoke in order to call TerminateThread.

  • User profile image


    Yep, you are 100% correct. During my testing I found that loading an unmanaged DLL can corrupt the managed process, and it is better to spin up a new process for each and every DLL I want to scan. This slows down the scanning process dramatically since I have more than 300 DLLs I need to check in this way (it could potentially go to thousands of DLLs), but to be sure, I need to start each scan in a known good state.

  • User profile image
    Matthew van Eerde

    > loading an unmanaged DLL can corrupt the managed process

    What is your managed process doing and why is loading an unmanaged .dll corrupting it?

  • User profile image

    @Matthew van Eerde:

    See this thread, and especially the 4th post.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.