使用Image.FromFile上的文件不会释放手柄 [英] Using Image.FromFile does not release handle on a file

查看:90
本文介绍了使用Image.FromFile上的文件不会释放手柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个连接的多个多图像TIFF文件到一个单一的多图像TIFF文件,并​​与删除源TIFF文件出了问题,因为Image类继续保持对他们的处理。

I'm doing a join of multiple multi-image tiff files to a single multi-image tiff file and have a problem with deleting the source tiff files, because the Image class continues to hold the handle on them.

我通过阅读Image.FromFile TIFF图像:

I'm reading a tiff image through Image.FromFile:

Bitmap resultTiff = (Bitmap) Image.FromFile(strImageFile);

在这之后我读了所有其他的TIFF图像以同样的方式,并把它们添加到生成TIFF图像。

After which I read all other tiff images the same way and append them to the resulting tiff image.

当我完成我用这个code释放引用,并保存生成的文件:

When I finish I use this code to release references and to save resulting file:

ep.Param[0] = new EncoderParameter(enc, (long) EncoderValue.Flush);
resultTiff.SaveAdd(ep);
resultTiff.Dispose();

现在的问题是,这些文件句柄的仍然存在的(因此文件不能被删除),除非我称之为 GC.Collect的() resultTiff.Dispose()调用之后。

Now the problem is that the handle on the files still exists (and therefore files can't be deleted) unless I call the GC.Collect() after the resultTiff.Dispose() call.

您可以想像,我不觉得通过调用GC很舒服,所以有实现这一目标的任何其他方式?

You can imagine that I don't feel very comfortable by calling GC, so is there any other way of achieving this?

推荐答案

要解决 Image.FromFile 的问题,其中它留下的文件句柄开放的最好方法是使用 Image.FromStream 代替。

The best way to solve the issue with Image.FromFile wherein it leaves file handles open is to use Image.FromStream instead.

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
   using (Image original = Image.FromStream(fs))
   {
      ...

使用一个明确的Dispose(),一个采用()语句,或将其值设置为null,直到垃圾收集情况并不能解决问题。强制垃圾收集发生通常是一个坏主意。

Using an explicit Dispose(), a using() statement or setting the value to null doesn't solve the issue until a garbage collection happens. Forcing a garbage collection to happen is generally a bad idea.

这篇关于使用Image.FromFile上的文件不会释放手柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆