热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

何时处置物体?C#

如何解决《何时处置物体?C#》经验,为你挑选了1个好方法。



1> Dmitry Byche..:

我们通常会将其包裹 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 明确地打电话.请注意, 您提供的两个代码摘录都会导致资源泄漏,如果是someCondition2someCondition3.

如果要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
        }        
    }     
}


推荐阅读
author-avatar
mobiledu2502897273
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有