一段时间后 P/Invoke 速度变慢

发布于 2024-12-10 16:15:21 字数 482 浏览 0 评论 0原文

我正在使用一个 C# 库,它的作用类似于非托管库的包装器。该库依赖于 P/Invoke。

我遇到了一些奇怪的事情:在我的 WinForms 应用程序中,我有一个按钮,当我按下该按钮时,它会从 1 迭代到 N,并且在每次迭代中,它都会调用该库。

每次我按下按钮(不关闭应用程序)时,从函数调用方法的时间在第一次迭代中是恒定的(大约半秒),但是对于其余的迭代,它变化很大,范围从半秒到至约2分钟。

每次迭代的工作都有些相同,所以这是不可理解的。

我注意到当库调用非托管函数时会发生这种缓慢的情况。

知道它是什么以及如何改进吗?

提前致谢!

-编辑- 请注意,每次我再次按下按钮时,循环的第一次迭代很快,但我正在调用的对象已经初始化(它是一个全局静态变量)!

-edit2- 到目前为止,我设法通过从专用线程完成对非托管函数的所有调用来解决该问题。但是,我仍然不明白为什么主 GUI 线程无法处理它(没有其他线程进行调用)。

I'm using a C# library which acts like a wrapper for an unmanaged library. This library relies on P/Invoke.

I'm experiencing something strange: in my WinForms application, I have a button which, when I press, it iterates from 1 to N and, in each iteration, it makes a call to this library.

Everytime I press the button (without closing the application), the time to call the method from the function is constant for the first iteration (about half second) but, for the remaining ones, it varies a lot, ranging from that half second up to about 2 minutes.

The work in each iteration is somewhat the same, so it's not understandable.

I've noticed that this slowness happens when the library calls the unmanaged function.

Any idea of what it can be and how can I improve this?

Thanks in advance!

-edit- Note that everytime I press the button again the 1st iteration of the loop is fast but the object that i'm calling is already initialized (it is a global static variable)!

-edit2- So far I managed to fix the problem by having all calls to the unmanaged function being done from a dedicated thread. However, I still didn't get why the main GUI thread couldn't handle it (there weren't other threads doing calls).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉薄对峙 2024-12-17 16:15:21

P/Invoke 应该只是一个普通的库调用操作。您的意思是,从托管到非托管的转变是问题所在。然而,我从来没有发现这是一个问题。

更有可能的是本机代码库停滞了。也许等待资源被释放,例如互斥锁或文件锁,这会在以后的调用中超时?
确保您的函数原型是正确的,并且您没有因为堆栈不平衡或类似情况而收到异常。

P/Invoke should simply be a normal library call operation. What you are implying is that the transition from managed to unmanaged is the issue. However, I have never found this to be an issue.

It is more likely the native code library which is stalling. Perhaps waiting for a resource to be freed, such as a mutex or file lock, which times out on the later invocations?
Make sure your function prototype is correct, and that you are not receiving exceptions because of stack imbalance or equivalent.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文