何时处置物体?C#

Ahm*_*mad 3 c# dispose for-loop image bitmap

我写了一个for-loop,在其中我声明了一个新的Image,所以我Dispose应该每次都在内部for循环中,或者一旦它完成了,那有什么区别?

这是一个明确的例子,我应该使用它:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要么:

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();
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 6

我们通常会将其包裹 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么我们不应该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
        }        
    }     
}
Run Code Online (Sandbox Code Playgroud)