如何等待文件被另一个外部进程释放? [英] How to wait for a file to be released by another external process?

查看:47
本文介绍了如何等待文件被另一个外部进程释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Processstart() 使用 PDFCreator 命令行创建文件.我使用 WaitForExit() 等待一段时间,否则我 Kill 进程并再次使用 WaitForExit().

I am creating a file using a PDFCreator command line using Processand start(). I wait for a sometime using WaitForExit() else I Kill the process and use WaitForExit() again.

经过这些步骤后,有时会创建输出文件,有时不会.所以我检查 File.Exist() 并访问输出文件.

After these steps sometimes the output file is created and sometimes not. So I check if the File.Exist() and access the output file.

我面临的问题是,即使创建文件的进程被终止或返回,有时该文件正被另一个 Process(可能是由 PDFCreator 创建的其他进程)使用Spooler 我不确定)

The issue I am facing is that even though the process creating the file is either killed or returned , sometimes this file is being used by another Process (probably some other process created by PDFCreator or a Spooler I am not sure)

所以我 Wait() 等待 3 秒,然后 poll 再次尝试 x 次,然后抛出我失败的例外.

So I Wait() for 3 seconds and poll again for x number of tries, then throw my exception for a failure.

我需要移动创建的文件,我需要检查文件是否存在,然后等待使用它的另一个进程释放它或者(可能找到哪个进程正在使用它并杀死它?).如果文件没有退出,我可以继续失败案例.

I need to move the created files, and I need to check that if the file exists, then wait until the other process using it releases it or (probably find which process is using it and kill it?). If the file does not exit, I can just proceed for failure case.

怎么做?

我可能可以尝试移动,然后如果另一个进程的异常正在使用它,那么我可以pollwait.

I can probably try to move, then if an exception for another process is using it then I can poll and wait.

但是有什么干净的方法吗?我不确定为什么即使在 Process 已被终止或返回后仍在使用该文件.

But any clean way approach? I am not sure why the file is in use even after the Process has been killed or returned.

推荐答案

您的根本问题可能是您在创建过程完成任务之前使用了kill".理想情况下,您应该等待完成后再继续,否则您会遇到像现在这样的锁定.

Your root issues is probably the fact that you are using "kill" on your creation process before it has completed its task. Ideally you should wait for completion before proceeding or you will experience lockouts like you are getting now.

也就是说,为了检查文件是否正在使用并且可以移动,您可以尝试使用取自 此处:

That said in order to check if the file is in use and available to be moved you can try using this code taken from here:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

这篇关于如何等待文件被另一个外部进程释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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