Cancel unmanaged DLL call

I have an unmanaged DLL with a function that can work for a long time if the input parameter is a large value, sometimes this is desirable, but not always.

How can I call this function in C # so that I can interrupt it if necessary?

So far, I tried to put the call in a separate thread, but neither interruption nor interruption seemed to terminate the process, which runs on 100% of the CPU until the dll is complete.

Is it possible to shut down dll code?

+12
multithreading c # dll unmanaged abort
May 6 '10 at
source share
2 answers

An unmanaged code is canceled only if it is an โ€œidle wait stateโ€. It will not be when it burns 100% of the processor cycles. P / Invoking TerminateThread will work, assuming you can get a handle to the thread, which .NET makes it very difficult. In any case, this will not help; you will be leaking a stack of threads. On one megabyte, you quickly run out of virtual memory. Even if this is only a random need, you can still face serious problems, because the thread has a mutated global state of the program, and you do not know how to restore it.

The only good way to break unmanaged code is to run it in a separate process and run it in the head using Process.Kill (). The operating system will clean the shrapnel. You will need to write a small hosting program for the DLL and use one of the means of interaction between the processes to talk to him. Sockets, named pipes, .NET remoting, WCF, select.

+23
May 6 '10 at 2:35 a.m.
source share

From MSDN

If Abort is called in a managed thread while it is running unmanaged code, a ThreadAbortException is not thrown until the thread returns to the managed code.

So, it seems that interruption of the controlled flow is impossible.
Alternatively, you can try to run an unmanaged thread using the Win32 API CreateThread() , WaitForSingleObject() and TerminateThread() . Use captions here .

I have not tried this myself, but it certainly introduces some risks, since you cannot determine at what point in execution you are killing the thread. It can also lead to a drain of resources. MSDN lists some side effects in the TerminateThread() directory.

In general, I would advise against such an interruption. You may have the option to modify an unmanaged DLL to provide a graceful undo.

+4
May 6 '10 at 2:04
source share



All Articles