首页 > 解决方案 > 如何处理 OutOfMemoryException

问题描述

在我的应用程序中,我有类似的东西:

static void Main(string[] args)
{
  for(int i=0;i<1000;i++){
   MyObj mo=new MyObj();
   }
 }

i=536我得到:Unhandled Exception: OutOfMemoryException

我试图修改为:

 for(int i=0;i<1000;i++){
   MyObj mo=new MyObj();
   mo=null;
   }

如何正确处理此异常?

MyObj 类大致如下:

    readonly string _url;
    readonly string _username;
    readonly string _password;
    //more properties here
    public MyObj(string username , string passowrd , string host )
    {
        _url = $"https://{host}";
        _username = username;
        _password = passowrd;

    }

    //upload file to server
    private void Upload(string path){
     //some code that upload the file
    }

    //get json string about htis file
     private void Info(string session){
      //some code here
     }

标签: c#out-of-memory

解决方案


根据我们掌握的少量信息,我建议在 MyObj 上实现 IDisposable,然后调整 for 循环:

for(int i=0;i<1000;i++)
{
    using(MyObj mo=new MyObj())
    {
        //Do something here
    }
}

MyObj 看起来像:

class MyObj : IDisposable
{
    public void Dispose()
    {
       // Dispose of unmanaged resources.
       Dispose(true);
       // Suppress finalization.
       GC.SuppressFinalize(this);
    }   
}

推荐阅读