首页 > 解决方案 > 什么时候处理对象?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();
}

标签: c#imagefor-loopbitmapdispose

解决方案


我们通常包装 IDisposableusing保证实例(即非托管资源)将被风雨无阻地处置。如果你想在内循环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
        }        
    }     
}

推荐阅读