How to get the amount of memory used by an applica

2019-01-17 20:31发布

问题:

Possible Duplicate:
How to get memory available or used in C#

I want to visualize the memory which is used by my application in the statusbar of my application. I am searching for a memoryleak - but I don't know where. Now, my idea is to visualize the used memory in the statusbar so that I can see it while I am working with the application and find the part, where the problem occurs and then I can profiling this.

Can someone give me some help, how can I get the used memory.

回答1:

You can use the following function (The true parameter tells the GC to perform a collection first):

long memory = GC.GetTotalMemory(true);


回答2:

You can try GC.GetTotalMemory:

It Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval > before returning, to allow the system to collect garbage and finalize > objects.


or

using System.Diagnostics;

Process currentProc = Process.GetCurrentProcess();

Once you have a reference to the current process, you can determine its memory usage by reading the PrivateMemorySize64 property.

long memoryUsed = currentProc.PrivateMemorySize64;


回答3:

If you want to monitor the memory used by your application, you do not need to write code for that. Just use the performance counters from Windows (http://www.codeproject.com/Articles/8590/An-Introduction-To-Performance-Counters). They'll provide the information you need with charts! There are lots of memory counters (http://msdn.microsoft.com/en-us/library/x2tyfybc.aspx), one of them will have the data you need and I guess it'll help you to find out when your app starts to use more memory than it should.

However, if you do need to put this information in your application, you can still use performance counters. .NET has classes in System.Diagnostics namespace to access their data. See this example: http://www.geekpedia.com/tutorial211_Using-Performance-Counters-in-Csharp.html



回答4:

Why not just monitor the memory usage with the TaskManager or with more advanced tools from Sysinternals and only after you determine what workflow raises the memory usage abnormally then profile the application with CLR Profiler or others.