I have been using WPF for a few years now and don't have any experience with anything but managed code. I started writing an app that uses a lot of win32 interop and i started wondering if i was leaking memory or generally doing something stupid that i didn't know about... So i thought i would seek some advice!
Is there any gotchas/tips/tricks when using win32 calls inside managed code?
I am mostly interested in memory/garbage collection but any other tips are welcome!
There are no gotchas. You free all resources that you allocate (unless the documentation indicates that the call you make takes over the resource, relieving you from ownership), and that's all there is to it. GC doesn't enter into it at all.
As a tip, System.Runtime.InteropServices.SafeHandle is a stock helper class to use Win32 handles RAII-style.
Almost resource you allocate in Win32 has to be deallocated with the right API call, which is documented on the MSDN page for the allocation API.
This is an entirely manual process; garbage collection doesn't assist with this at all, although you can use SafeHandle or (last resort) finalizers.
At the very least, use IDisposable wrapper classes around any resources you allocate. In some cases, these already exist in Windows Forms.
You can use Perfmon or Task Manager to monitor the number of handles open in your process.
The main problem with win32 interop is (obviously) Linux/Mac OS incompatibility(Mono won't be able to help you yet if you have P/Invokes to win32 libraries).
Apart from that, I'm not aware of any problems. Unless, of course, the function you're calling itself leaks memory.
You have to be a bit careful if you need to call GetLastError to determine why a win32 call failed. This page provides a detailed description.
Related
I was wondering if there is any way to allocate memory in a process and have that memory be r/w & executable?
I found System.Runtime.InteropServices.Marshal.AllocHGlobal, dunno if that the thing I am looking for, if so then how does it work? I don't really understand it, where is the allocated memory located.
This is a task for the VirtualAlloc and VirtualProtect API calls rather than the interop marshaller. You will have to declare them [DllImport]. Hhowever this entire process would be painful enough that I would seriously consider using a different language. Perhaps a c++ project that provides just the interop calls you need while the UI remains in C#. (Honestly, interop stuff is the only area where I see c++ and .net working well together).
How can I watch a specific process to know what resources it uses at runtime (such as sounds, pictures, cursors, and registry keys)?
I have to do that programmatically using C# (e.g. using the Windows API or any third party library).
Any help is appreciated. Thanks.
I would stick to performance counters. There are ones for
Memory
GDI Handles (Bitmap, Font, ...)
Handles (File, Registry Key, Event, Mutex, Socket, Process, ...)
Windows (User Objects)
The exact type cannot be determined by using performance counters but it can give you a hint if you are leaking something. If you want to know which handles you can use handles from SysInternals which will give you a nice per process output which you can parse.
If you want to fix the handle leaks then you need to use a debugger (Windbbg) and use the !handle extension to start tracking all aquire/release call stacks for each handle so you can get latter a statistics which handles have been allocated but not freed yet.
Your question is a little to broad because the exact tactic to nail a resource leakage is dependant on the nature of the leak. EasyHook is a good solution to track all resource aquire/release calls and record them automatically.
If you want to automate a debugger with e.g. C# you can use http://wmemoryprofiler.codeplex.com/ which is bascially a managed wrapper around Windbg which even allows you to self debug your application.
When you just want to learn the principles how to get your hands on scattered data for various resources you should read the code of Process Hacker.
Do you want the GDI objects or Win32 handles?
Win32 handles can be obtained using the NtQuerySystemInformation WinAPI function. You can find the C# code for handle-related tasks in these ProcessHacker sources: http://sourceforge.net/p/processhacker/code/HEAD/tree/1.x/trunk/ProcessHacker.Native/Windows.cs
EasyHook will allow you to intercept Windows API calls. Here's a simple example for all file accesses made by a process. Registry calls also seem to be supported.
While using SlimTune to profile a C# application, I find that when profiling native functions is enabled there are lots of entries for a function called "CoUninitializeE." CoUninitialize seems to be related to COM objects, however I'm not directly using any Com objects, and Google has no information about the version ending with an E.
Does anyone have knowledge of what this function is/how to reduce the amount of time spent on it? (For instance, is it related to memory management, so that reducing memory allocations or deallocations would help?)
Edit
It appears the function's name is actually "CoUninitializeEx" and that SlimTune is just chopping off a letter for some reason. I still would appreciate knowledge of what leads to this function being called.
CoInitalizeEx() and CoUninitialize() are pretty core in Windows programming. They respectively initialize and shutdown COM on a thread. The CLR calls these functions automatically before and after a Thread runs. It is pretty hard to avoid using COM in a .NET program, it is the basic extensibility model for native Windows code. Quite invisible, thanks to the many wrapper classes in the .NET framework that hides the plumbing.
The generic diagnostic is that you use a lot of threads. Yes, expensive. The thread pool is a workaround.
I have an unmanaged C++ exe that I could call from inside my C# code directly (have the C++ code that I could make a lib) or via spawning a process and grabbing the data from the OutputStream. What are the advantages/disadvantages of the options?
Since you have source code of the C++ library, you can use C++/CLI to compile it into a mixed mode dll so it is easy to be used by the C# application.
The benefit of this will be most flexible on data flow (input or output to that C++ module).
While running the C++ code out of process has one benefit. If your C++ code is not very robust, this can make your main C# process stable so as not to be crashed by the C++ code.
The big downside to scraping the OutputStream is the lack of data typing. I'd much rather do the work of exporting a few functions and reusing an existing library; but, that's really just a preference.
Another disadvantage of spawning a process is that on windows spwaning a process is a very expensive (slow) operation. If you intend to call the c++ code quite often this is worth considering.
An advantage can be that you're automatically more isolated to crashes in the c++ program.
Drop in replacement of the c++ executable can be an advantage as well.
Furthermore writing interop code can be big hassle in c#. If it's a complicated interace and you decide to do interop, have a look at c++/cli for the interop layer.
You're far better off taking a subset of the functions of the C++ executable and building it into a library. You'll keep type safety and you'll be able to better leverage Exception Handling (not to mention finer grain control of how you manage the calls into the functions in the library).
If you go with grabbing the data from the OutputStream of the executable, you're going to have no visibility into the processes of the executable, no real exception handling, and you're going to lose any type information you may have had.
The main disadvantage to being in process would be making sure you handle the managed/native interactions correctly.
1)
The c++ code will probably depend on deterministic destruction for cleanup/resource freeing etc. I say probably because this is common and good practice in c++.
In the managed code this means you have to be careful to dispose of your c++ cli wrapper code properly. If your code is used once, a using clause in c# will do this for you. If the object needs to live a while as a member you'll find that the dispose will need to be chained the whole way through your application.
2)
Another issue depends on how memory hungry your application is. The managed garbage collector can be lazy. It is guaranteed to kick in if a managed allocation needs more space than is available. However the unmanaged allocator is not connected in anyway. Therefore you need to manaully inform the managed allocator that you will be making unmanaged allocations and that it should keep that space available. This is done using the AddMemoryPressure method.
The main disadvantages to being out of process are:
1) Speed.
2) Code overhead to manage the communication.
3) Code overhead to watch for one or other process dying when it is not expected to.
We're migrating a C++ application to .Net CF. We need to monitor both the UI and several external events. I therefore wonder if we can get the same functionality of MsgWaitForMultipleObjects in the unmanaged world also in the managed world?
Edit: P/Invoke is not the complete answer I'm seeking, since what I meant was that we want the full functionality of what we have in the unmanaged world, meaning that when input messages are pumped, events and other sync objects are also monitored. We don't have access to the message pump in .Net, for obvious reasons. So where do we hook ourselves in for P/Invoking MsgWaitForMultipleObjects?
What we'll need to do is actually to skip Application.Run(Form) and roll our own message loop as in the unmanaged world. Then we can use MsgWaitForMultipleObjects as described in the original question. This has been done also in SDF.