简体   繁体   English

C#.Net Close应用程序超出内存使用量

[英]C# .Net Close application on exceeding memory usage

I have an application which deals with huge amount of in-memory data. 我有一个处理大量内存数据的应用程序。 Now, sometimes what happens is that memory limit of 2GB/app is reached and my program hangs. 现在,有时会发生什么情况,即达到2GB / app的内存限制,并且我的程序挂起。 The memory usage in the task manager goes haywire (continuously fluctuates from 2GB to 6GB) What I want is that when the memory usage reaches a particular limit, the program should gracefully exit. 任务管理器中的内存使用情况非常混乱(从2GB到6GB连续波动)。我想要的是,当内存使用量达到特定限制时,程序应该正常退出。 I don't want manual intervention of user killing the app. 我不希望用户手动杀死应用程序。 Is this possible? 这可能吗?

You should allocate a background monitoring thread, which polls System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 and then acts accordingly to the size returned. 您应该分配一个后台监视线程,该线程轮询System.Diagnostics.Process.GetCurrentProcess()。PrivateMemorySize64,然后根据返回的大小进行操作。

Eg. 例如。

public class MonitoringThread : Thread{
...

bool working = true;
void run(){
   while(working){
      long size = Process.GetCurrentProcess().PrivateMemorySize64;
      if (size > 2000000000){
         //do anything
      }
      else {
         try{
            Thread.Sleep(1000);
         }
         catch{}
      }
   }
}

}

Please note that I just wrote this code in this page, so it may be not too accurate :) 请注意,我只是在此页面中编写了此代码,所以它可能不太准确:)

You could use Garbage Collection Notifications to be alerted when a full Garbage Collection has completed. 完整的垃圾收集完成后,您可以使用Garbage Collection Notifications来发出警报。

In response to that, you could check GC.GetTotalMemory() to see how much memory is currently used, and take the appropriate action if it is too high. 对此,您可以检查GC.GetTotalMemory()以查看当前使用了多少内存,如果内存过多,请采取适当的措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM