Process.Start()未释放文件句柄

时间:2017-02-25 01:32:58

标签: c# process

我有一些代码正在使用GraphViz的点程序创建节点图的PNG文件。这第一次通过代码完美地工作。但是,如果我再次尝试运行该方法,则会失败,因为该文件仍被Windows视为正在使用。

以下是启动dot.exe进程的相关代码:

private void MakePng()
{
    string args = "-o" + graphPath + " -Tpng  " + dotPath;

    Process process = new Process();

    ProcessStartInfo info = new ProcessStartInfo();
    info.FileName = VizGraphPath;
    info.Arguments = args;
    info.UseShellExecute = false;
    info.CreateNoWindow = true;

    process.StartInfo = info;
    process.EnableRaisingEvents = true;
    process.Exited += new EventHandler(Process_Exited);
    process.Start();

}
private void Process_Exited(object sender, EventArgs e)
{
   UpdateCanvas();
}

名为xxxPath的各种字符串变量只是正确文件路径的静态字符串。当程序启动并运行此代码时,一切都运行良好。但是如果我重置我的图并尝试再次运行这组代码,则无法创建新的PNG。旧的还在那里。为了测试一些东西,我添加了这一行:

private void MakePng()
{
    string args = "-o" + graphPath + " -Tpng  " + dotPath;
    File.Delete(graphPath);

第一次通过。但第二次它抛出一个Exception声明文件仍在使用中。所以我猜不知道当我开始退出的进程时,它创建的文件句柄仍然在使用,即使它已经退出了?有关如何弄清楚为何仍在使用或如何修复它的任何建议?

我的UpdateCanvas函数也在访问被锁定的文件:

public void UpdateCanvas()
{
  Bitmap image = new Bitmap(graphPath);
  pbCanvas.Image = image;  
}

从文件加载位图以释放文件时,我是否需要一些东西? 确实是Bitmap锁定了文件。我必须在解锁文件之前处理它。

2 个答案:

答案 0 :(得分:1)

流程类实现IDisposable,因此您需要设置资源。此外,您可以添加WatForExit方法以确保您的过程完成:

{{1}}

答案 1 :(得分:1)

您的文件被new Bitmap锁定。 用以下内容重写:

public void UpdateCanvas()
{
    Image img;
    using (var bmpTemp = new Bitmap(graphPath))
    {
        img = new Bitmap(bmpTemp);
    }
    pbCanvas.Image = img;  
}