C#/C++ - Memory Leak
I have a C++ DLL (no source code / .pdb available for C++ DLL) in production. It is being called by a C# application using P/Invoke mechanism. Now, there is a leak in the C++ DLL. And, after executing for 20-22 times, the application crashes everytime. Now, how can I gracefully handle this such that I continue to开发者_JAVA百科 use the C++ DLL with the leak from C# App?
In order to me, if it is absolutely impssible to modify / replace the c++ dll, and you are sure there is no problem in the PInvoke layer, the only option iif the performance remain acceptable, is to insulate the dll call in an executable communicating with the main one with some IPC ( Remoting for example ) so you can force recycling in the hosting process. This approach would work only if the way you call the c++ dll is not too granular. A way to do this with as less effort as possible is to crete a web service hosting the C++ call ( if calling the C++ as a web service is feasible always in term of performance ), host it in a special appdomain and specify for it a reciclying based on memory amount. If this is not possible, the solution propsed by SeeSharp in his comment below is probably the best one.
Without seeing the interop, I would suggest that the C++ is returning a structure/class that you must free.
Run the C++ code in a separate process, that way when the memory leak accumulates to an unacceptable level, you can restart it without affecting the rest of your application.
You may want to isolate your calls to this function in a customUnmanaged DLLs are not unloaded with AppDomainsAppDomain
. Unload/recreate theAppDomain
from time to time (or maybe each time).- You could wrap your library in an out of process COM component (example here). You could then release/recreate this component at will.
- You may also want to work in a place where they don't throw their source code away...
精彩评论