Process Memory Size - Different Counters

前端 未结 7 2008
闹比i
闹比i 2020-12-30 04:46

I\'m trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes).

I\'m using:

Process.GetCurrentProc         


        
7条回答
  •  北海茫月
    2020-12-30 04:56

    To get the value that Task Manager gives, my hat's off to Mike Regan's solution above. However, one change: it is not: perfCounter.NextValue()/1000; but perfCounter.NextValue()/1024; (i.e. a real kilobyte). This gives the exact value you see in Task Manager.

    Following is a full solution for displaying the 'memory usage' (Task manager's, as given) in a simple way in your WPF or WinForms app (in this case, simply in the title). Just call this method within the new Window constructor:

        private void DisplayMemoryUsageInTitleAsync()
        {
            origWindowTitle = this.Title; // set WinForms or WPF Window Title to field
            BackgroundWorker wrkr = new BackgroundWorker();
            wrkr.WorkerReportsProgress = true;
    
            wrkr.DoWork += (object sender, DoWorkEventArgs e) => {
                Process currProcess = Process.GetCurrentProcess();
                PerformanceCounter perfCntr = new PerformanceCounter();
                perfCntr.CategoryName = "Process";
                perfCntr.CounterName = "Working Set - Private";
                perfCntr.InstanceName = currProcess.ProcessName;
    
                while (true)
                {
                    int value = (int)perfCntr.NextValue() / 1024;
                    string privateMemoryStr = value.ToString("n0") + "KB [Private Bytes]";
                    wrkr.ReportProgress(0, privateMemoryStr);
                    Thread.Sleep(1000);
                }
            };
    
            wrkr.ProgressChanged += (object sender, ProgressChangedEventArgs e) => {
                string val = e.UserState as string;
                if (!string.IsNullOrEmpty(val))
                    this.Title = string.Format(@"{0}   ({1})", origWindowTitle, val);
            };
    
            wrkr.RunWorkerAsync();
        }`
    

提交回复
热议问题