1

我想监视一个文件并找出它何时不再生长。我执行一个外部程序

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 共享中很糟糕。

4

1 回答 1

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++;
        }
    }
于 2013-01-22T08:03:52.450 回答