C# - GC.GetTotalMemory() Question
I'm creating a C# based Windows service that will run 24x7 for months on end. I'd like to be able to track general memory usage of my service. It doesn't need to be exact down to the byte. A general amount allocated will suffice. I'll be monitoring this for trends in memory consumption. Is GC.GetTotalMemory() an appropriate way to monitor this?
I'm aware of Performance Monitor and the use of counters. However, this service is going to be running on at least 12 different servers. I don't want to track PM on 12 different servers. The service will persist all performance and memory usage information, from all instances, 开发者_如何学Cto a central DB to avoid this, and for easier analysis.
Only if it's a purely managed-memory application. If any of it is calling off to unmanaged code, the memory allocated there will never be registered with the garbage collector (unless someone remembers to call GC.AddMemoryPressure
).
GC.GetTotalMemory
retrieves the amount of memory thought to be allocated. It only knows about memory allocated by the managed components, unless you call GC.AddMemoryPressure
to tell it about other memory allocated.
You can get a better idea of the real amount of memory allocated by reading Process.WorkingSet64
, Process.VirtualMemory64
, and other such properties of the Process
class. Just call Process.GetCurrentProcess
, and then get what you need.
That said, you're probably better off using the performance counters.
This isn't a direct answer to your question, but was prompted by your intent to keep your service running 24x7 for months.
I would be very aware of heap fragmentation. See this article for an explanation
Use performance counters. You can set them up to log to file.
Alternatively you can read performance counters in your code, and save out the data to a central location.
精彩评论