c# - 什么时候处理对象?C#
问题描述
我写了一个for
-loop ,在里面我声明了一个 new Image
,所以我Dispose
应该每次都在内部for
-loop 里面,或者一旦它全部完成,有什么区别?
这是一个让事情变得清晰的例子,我应该使用这个:
for (int i = 0; i < 10; i++)
{
Image imgInput = new Image();
for (int j = 0; j < 100; j++)
{
// Here is a code to use my image
Image.Dispose();
}
}
或者:
for (int i = 0; i < 10; i++)
{
Image imgInput = new Image();
for (int j = 0; j < 100; j++)
{
// Here is a code to use my image
}
Image.Dispose();
}
解决方案
我们通常包装 IDisposable
成using
以保证实例(即非托管资源)将被风雨无阻地处置。如果你想在内循环Image
之外声明:
for (int i = 0; i < 10; i++)
{
using (Image imgInput = new Image())
{
for (int j = 0; j < 100; j++)
{
...
// In all these cases the resource will be correctly released:
if (someCondition1)
break;
...
if (someCondition2)
return;
...
if (someCondition3)
throw new SomeException(...);
...
// Here is a code to use my image
}
}
}
这就是为什么我们不应该Dispose
显式调用. 请注意, 您提供的两个代码摘录都会在或的情况下导致资源泄漏。someCondition2
someCondition3
如果要Image
在嵌套循环中声明,则使用相同的方案:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 100; j++)
{
using (Image imgInput = new Image())
{
// Here is a code to use my image
}
}
}
推荐阅读
- node.js - 节点猫鼬模型第一个参数
- sql - SQLite:如何使用与另一列的两行之间的差异值更新列?
- javascript - 使用 react-transition-group 退出和进入动画的问题
- typescript - 在不重复的情况下弃用枚举值
- python - Python DataFrame df.to_json(orient='split') - 不维护列标签的顺序
- angular - 如何在 Ionic 3 中重置 Ion-Select 表单域?
- c - 防止字符串化输出中的空格
- random - 从具有概率的列表中选择 X 个元素
- mysql - 我可以将用户输入语言转换为数据库的默认排序规则吗?
- java - 如何更改进度条状态