中止对非托管 DLL 的调用 [英] Abort call to unmanaged DLL

查看:31
本文介绍了中止对非托管 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 代码?

Is it possible to terminate the running dll code?

推荐答案

非托管代码只有在处于警报等待状态"时才能中止.它不会在燃烧 100% cpu 周期时发生.P/Invoking 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.

中止非托管代码的唯一好方法是在单独的进程中运行它,并使用 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.

这篇关于中止对非托管 DLL 的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆