中止调用非托管的DLL

问题描述:

我有与可以很长时间运行,如果输入参数是一个较大的值的功能的非托管的DLL,有时这是可取的,但并非总是如此。

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

我如何在C#中调用这个函数,这样我可以在需要的时候放弃了吗?

How can I in c# call this function so that I can abort it when needed?

到目前为止,我已经试图把呼叫一个单独的线程,但是没有中断,也没有放弃似乎停止的过程中,它以100%的CPU,直到DLL完成运行。

So far I have tried to put the call in a separate thread, but neither interrupt nor abort seem to stop the process, which runs at 100% CPU until the dll is done.

是否有可能终止正在运行的DLL code?

Is it possible to terminate the running dll code?

未管理code仅可中止,如果它是一个可报警等待状态。当它燃烧100%的CPU周期也不会。 P / TerminateThread中调用会工作,假设你可以得到线程处理,这使得.NET非常困难。它无论如何也不会帮助,你会泄漏线程堆栈。在一兆字节,你会很快的虚拟内存用完。即使这只是偶尔需要,你仍有可能遇到的重大问题,因为线程已经变异全球计划状态,你不知道如何恢复它。

Unmanaged code is only abortable if it is an "alertable wait state". It won't be when it is burning 100% cpu cycles. P/Invoking TerminateThread would work, assuming you could obtain the thread handle, which .NET makes very difficult. It won't help anyway, you'll leak the thread stack. At one megabyte, you'll quickly run out of virtual memory. Even if this only an occasional need, you're still liable to run into major problems since the thread has mutated global program state and you don't know how to restore it.

中止非托管code中的唯一的好办法就是在一个单独的进程中运行它,并Process.Kill拍它的头()。操作系统将清理弹片。你需要写一个小程序托管的DLL和使用的过程中互操作的设施之一,它对话。套接字,命名管道,.NET远程,WCF,随你挑。

The only good way to abort unmanaged code is to run it in a separate process and shoot it in the head with Process.Kill(). The operating system will clean up the shrapnel. You'll need to write a little hosting program for the DLL and use one of the process interop facilities to talk to it. Sockets, named pipes, .NET remoting, WCF, take your pick.