get memory space in c#

2019-09-20 01:04发布

How would you do this in c#, an example in c++ is:

void PrintMemoryInfo( DWORD processID )
{
     std::ofstream fs("d:\\processInfo.txt"); 
     fs<<"Information of Process:\n";

    HANDLE hProcess;
    PROCESS_MEMORY_COUNTERS pmc;
    fs<<"\nProcess ID: %u\n"<<processID;

    hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION |
                                    PROCESS_VM_READ,
                                    FALSE, processID );
  if (NULL == hProcess) return;

    if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )    {



        fs<< "\tPageFaultCount: 0x%08X\n" << pmc.PageFaultCount;
        fs<< "\tYour app's PEAK MEMORY CONSUMPTION: 0x%08X\n"<<pmc.PeakWorkingSetSize;
        fs<< "\tYour app's CURRENT MEMORY CONSUMPTION: 0x%08X\n"<< pmc.WorkingSetSize;
        fs<< "\tQuotaPeakPagedPoolUsage: 0x%08X\n"<< 
                  pmc.QuotaPeakPagedPoolUsage;
        fs<< "\tQuotaPagedPoolUsage: 0x%08X\n"<< 
                  pmc.QuotaPagedPoolUsage;
        fs<< "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n"<< 
                  pmc.QuotaPeakNonPagedPoolUsage;
        fs<< "\tQuotaNonPagedPoolUsage: 0x%08X\n"<< 
                  pmc.QuotaNonPagedPoolUsage;
        fs<< "\tPagefileUsage: 0x%08X\n"<< pmc.PagefileUsage; 
        fs<< "\tPeakPagefileUsage: 0x%08X\n"<< 
                  pmc.PeakPagefileUsage;                  
    }
    fs.close();
    CloseHandle( hProcess);
}

int main( )
{
  PrintMemoryInfo( GetCurrentProcessId() );

    return 0;
}

but in c#?...

2条回答
Deceive 欺骗
2楼-- · 2019-09-20 01:14

You should be able to do this using System.Diagnostics.Process class. Please, have a look at: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

查看更多
倾城 Initia
3楼-- · 2019-09-20 01:29

Here are a few other articles that describe getting a running application's memory footprint:

Poll C# app's memory usage at runtime?

Memory usage in C#

TL;DR;

// get the current process
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();

// get the physical mem usage
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
查看更多
登录 后发表回答