c# - 如何处理 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
}
解决方案
根据我们掌握的少量信息,我建议在 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);
}
}
推荐阅读
- forms - MS Access 表单:母亲组合框在表中未正确显示,但女儿组合是
- javascript - jquery复选框如果语句不再工作
- libvlcsharp - 为统一执行 VLC
- powershell - 为文档库中的选择列设置默认值
- javascript - ACE编辑器双击后获得选定的单词
- bash - 未找到 ZSH 命令
- amazon-ecs - 是否可以通过 Fargate 1.3.0 或 1.4.0 将主机条目添加到 /etc/hosts 文件?
- mysql - 有条件地插入表的方法(MariaDB)
- javascript - 使用 app.response 获取文本,然后附加到来自另一个字段的文本
- ios - SWIFT:用键盘向上移动的UIView,在初始移动后移动非常奇怪,不会回落