Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
何时处置物品?C#_C#_Image_For Loop_Bitmap_Dispose - Fatal编程技术网

何时处置物品?C#

何时处置物品?C#,c#,image,for-loop,bitmap,dispose,C#,Image,For Loop,Bitmap,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

我为-循环编写了一个
,在这个循环中我声明了一个新的
图像
,所以我应该每次在内部
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();
    }
}
for(int i=0;i<10;i++)
{
Image imgInput=新图像();
对于(int j=0;j<100;j++)
{
//下面是使用我的图像的代码
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();
}
for(int i=0;i<10;i++)
{
Image imgInput=新图像();
对于(int j=0;j<100;j++)
{
//下面是使用我的图像的代码
}
Image.Dispose();
}
我们通常使用
IDisposable
包装到
中,以确保实例(即非托管资源)无论晴雨都能被处置。如果要在内部循环外部声明
图像

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方法,析构函数(终结器)负责释放资源。GC只清理托管资源。调用Bitmap.Dispose可以确保及时清理这些非托管资源,并且不会泄漏资源

通常情况下,如果析构函数超出范围,就会调用析构函数

在释放对的最后引用之前,始终调用Dispose 形象。否则,它正在使用的资源将不会被释放,直到 垃圾收集器调用映像对象的Finalize方法

你的第二种方法很有意义。您将在使用图像对象后删除它

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;我认为您需要显示一些代码,并描述您希望代码执行的操作。
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();
}