在我的应用中,我有类似的东西:
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
}
答案 0 :(得分:-1)
利用我们掌握的信息,我建议在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);
}
}