通过延迟操作查明文件是否仍在增长

时间:2013-01-22 07:39:40

标签: c# .net wpf

我想查看一个文件并找出它何时不再生成。 我执行外部程序

Process.Start(
    "procdump.exe",
    string.Format(@"-ma {0} Output\{1}_RAW_DUMP.dump",
    processName,
    dt.ToString("yyyyMMdd-HHmmss")));

我需要知道这个过程何时完成它的工作。

所以我写了这个:

private void CheckDumpFile(DateTime startDateTime, IConfigHolder configHolder, List<string> results)
{
    var path = CheckExistensDumpFile(startDateTime);
    const int delayMs = 250;
    if (path == null)
    {
        Console.WriteLine("Dumpfile not ready yet, next try in 0.25s, now: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
        RetryAction(() => CheckDumpFile(startDateTime, configHolder, results), delayMs);
    }
    else
    {
        var fileInfo = new FileInfo(path);
        if (fileInfo.Length == 0)
        {
            Console.WriteLine("Dumpfile has no Length yet, now: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
            RetryAction(() => CheckDumpFile(startDateTime, configHolder, results), delayMs);
        }
        else
        {
            if (_lastLength == fileInfo.Length)
            {
                Console.WriteLine("Dumpfile is " + _lastLength + "bytes, starting analysis, now: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                ReadDumpFile(configHolder, path, results);
            }
            else
            {
                Console.WriteLine("Dumpfile is still growing, next try in 0.25s, now: {0}", DateTime.Now.ToString("HH:mm:ss.fff"));
                _lastLength = fileInfo.Length;
                RetryAction(() => CheckDumpFile(startDateTime, configHolder, results), delayMs);
            }
        }
    }
}

这个

public static void RetryAction(Action action, int delayMs)
{
    new Timer(obj => action(), null, delayMs, Timeout.Infinite);
}

这一直有效,直到文件缓慢变慢,我再调用一次'RetryAction'。不会有一个电话回来。

你知道什么是问题吗? 对我的案子有更好的解决方案吗?我忽略了FilWatcher,因为有人告诉我FileWatcher在ne9twork股票中很糟糕。

1 个答案:

答案 0 :(得分:0)

我也遇到过这个问题。我写了一个检查上次写入时间的方法,所以即使文件只增加一个字节,它仍然会被归类为使用中。

    /// <summary>
    /// Waits for completion of writing to a file.
    /// </summary>
    /// <param name="fullPath">The full path.</param>
    /// <param name="timeToWait">The time to wait on each attempt.</param>
    /// <param name="retryAttempts">The maximum number of retry attempts.</param>
    /// <param name="safetyBuffer">The safety buffer.</param>
    public static void WaitForFile(string fullPath, TimeSpan timeToWait, int retryAttempts, TimeSpan safetyBuffer)
    {
        var timesSkipped = 0;
        var info = new FileInfo(fullPath);
        var maxWriteTime = DateTime.Now.Add(-safetyBuffer);// no activity for a minute
        while (info.Exists && (info.LastWriteTime > maxWriteTime) && timesSkipped < retryAttempts) {
            Thread.Sleep(timeToWait);
            maxWriteTime = DateTime.Now.Add(-safetyBuffer);
            info.Refresh();
            timesSkipped++;
        }
    }