[英]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.