如何处理 OutOfMemoryException
How to handle 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 class 大致如下:
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
}
根据我们掌握的少量信息,我建议在 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);
}
}
在我的应用程序中,我有类似的东西:
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 class 大致如下:
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
}
根据我们掌握的少量信息,我建议在 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);
}
}