Search code examples
c#.netpinvokeunmanaged

Slow P/Invoke after some times


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).


Solution

  • 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.