繁体   English   中英

图像文件处理后不释放

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

我正在研究一个下载一些图像并将它们放在 arrarList 中以便稍后处理的项目。 以下代码部分是问题所在。 它适用于第一次下载,但以某种方式保存的文件图像在第一次下载后被锁定。 我似乎找不到解锁它的方法。 File.Delete("BufferImg"); 当“BufferImg”未在程序的其他任何地方使用时,给出错误说明该文件已被另一个进程使用。 我究竟做错了什么?

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;

}

以下行是未发布图像的原因:

IMBuffer.Add(img.Clone());

当您克隆通过资源(文件)加载的内容时,该文件仍附加到克隆的 object。 您将不得不使用 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();

这应该在您将文件加载到缓冲区后释放文件。

暂无
暂无

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

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