C# - 如何暂停程序直到图像文件被覆盖

C# - How to pause the program until an image file is done being overwritten

在我的程序中,有一个过程是这样的:

Save Image (Overwrite the existing one) -> Run OCR on this image -> Return string result

这个过程可以连续重复几次,如果没有 Thread.Sleep(),结果是:

1st iteration: Save img01 -> Run OCR on img01 -> return result of img01

2nd iteration: Save img02 to replace img01 -> still run OCR on img01 (old img) -> return result of img01 (old result)

(img01和img02共享同一个文件name/path)


因为流程中没有暂停,我注意到 OCR 将在 img01 而不是 img02 上进行,因为 img02 仍在保存。

我当前 PC 的不可靠工作方式是在保存图像和 运行 OCR 之间简单地设置一个 Thread.Sleep(1000)。 但是我可以想象这不是正确的解决方案,因为不同的计算机将花费不同的时间来保存图像,对吗?

如何让程序动态暂停并等待图像被完全覆盖后再继续下一步?

一种方法是这样的:

首先您应该检查 img02 是否存在以及文件当前是否正在使用。

为了检查 img02 是否存在,您可以这样做:File.Exists(path)

然后检查文件是否在使用中,类似:

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

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, 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;
}

如果文件没有被使用,那么您可以继续下一步。