Bri*_*anH 2 c# memory multithreading dispose picturebox
我正在编写一个将播放幻灯片的程序(除其他外)。幻灯片由backgroundWorker控制,并设置为while(true)循环,因此它将不断播放图像。我的问题是我不确定如何处置旧图像,以免它们占用内存(一段时间后程序会引发“内存不足异常”。如果我调用horPicBox.Image.Dispose(),那么它将之后,我将不再使用pictureBox。
有没有办法从内存中释放旧图像?如果我查看VS中的诊断工具,则每次图像更改时内存都会增加。

注意:ImagePaths是幻灯片图像的文件路径的列表。
这是backgroundWorker运行的代码:
private void PlayImages()
{
Random r = new Random();
int index;
Stopwatch watch = new Stopwatch();
while (true)
{
index = r.Next(imagePaths.Count);
horPicBox.Image = Image.FromFile(imagePaths[index]);
watch.Start();
while (watch.ElapsedMilliseconds < 5000)
{
}
watch.Stop();
watch.Reset();
//picWorker.ReportProgress(0);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以将progressChanged报告给UI线程,但是我不确定从UI线程(如果有的话)释放旧的图像需要做什么。提前致谢!!
图片数量和总大小是多少?horPicBox我认为将所有图像加载到数组中并将它们分配给它们比多次加载它们更好。要使用Dispose首先分配horPicBox.Image给临时对象,然后分配horPicBox.Image给null或下一个图像并Dispose在最后调用临时对象:
Image img = horPicBox.Image;
horPicBox.Image = Image.FromFile(imagePaths[index]);
if ( img != null ) img.Dispose();
Run Code Online (Sandbox Code Playgroud)
如果将图像存储到该类型的变量,然后设置图片框图像,然后像处理旧图像一样处理该怎么办?
Image oldImage = horPicBox.Image;
horPicBox.Image = Image.FromFile(imagePaths[index]);
oldImage.Dispose();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3757 次 |
| 最近记录: |