简体   繁体   English

图像文件处理后不释放

[英]image file is not released after it is disposed

I am working on a project that downloads some images and put them in a arrarList to be processed later.我正在研究一个下载一些图像并将它们放在 arrarList 中以便稍后处理的项目。 The following portion of code is where the problem is.以下代码部分是问题所在。 It works with first download, but somehow the file images were saving to is locked up after the first download.它适用于第一次下载,但以某种方式保存的文件图像在第一次下载后被锁定。 I can't seems to find a way to unlock it.我似乎找不到解锁它的方法。 File.Delete("BufferImg"); File.Delete("BufferImg"); is giving error saying the file is been used by another process when "BufferImg" was not used anywhere else of the program.当“BufferImg”未在程序的其他任何地方使用时,给出错误说明该文件已被另一个进程使用。 What am I doing wrong?我究竟做错了什么?

int attempcnt=0; 
if (ok)
 {
     System.Net.WebClient myWebClient = new System.Net.WebClient();
     try
     {
         myWebClient.DownloadFile(pth, "BufferImg");
         lock (IMRequest) { IMRequest.RemoveAt(0); }
         attempcnt = 0;
     }
     catch   // will attempcnt 3 time before it remove the request from the queue
     {
         attempcnt++;
         myWebClient.Dispose();
         myWebClient = null;
         if(attempcnt >2)
         {
             lock (IMRequest) { IMRequest.RemoveAt(0); }
             attempcnt = 0;
         }
         goto endofWhile;
     }
     myWebClient.Dispose();
     myWebClient = null;
     using (Image img = Image.FromFile("BufferImg"))
     {
         lock (IMBuffer)
         {
             IMBuffer.Add(img.Clone());
             MessageBox.Show("worker filled: " + IMBuffer.Count.ToString() + ": " + pth);
         }
         img.Dispose();
     }
 }
endofWhile:
 File.Delete("BufferImg");
 continue;

} }

The following line is why the image is not being released:以下行是未发布图像的原因:

IMBuffer.Add(img.Clone());

When you clone something loaded through a resource (file), the file is still attached to the cloned object.当您克隆通过资源(文件)加载的内容时,该文件仍附加到克隆的 object。 You will have to use a FileStream, like so:您将不得不使用 FileStream,如下所示:

FileStream fs = new FileStream("BufferImg", FileMode.Open, FileAccess.Read);
using (Image img = Image.FromStream(fs))
{
    lock (IMBuffer)
    {
        IMBuffer.Add(img);
        MessageBox.Show("worker filled: " + IMBuffer.Count.ToString() + ": " + pth);
    }
}
fs.Close();

This should release the file after you've loaded it in the buffer.这应该在您将文件加载到缓冲区后释放文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM