【问题标题】:Create a StreamReader/FileStream at the exact same time by two instances, throws exception File is being used by another process两个实例同时创建一个 StreamReader/FileStream,抛出异常 File is being used by another process
【发布时间】:2019-01-13 14:45:58
【问题描述】:

我正在根据 FileWatcher 事件读取网络位置中的文本文件。我有同一个程序的两个实例读取文件,当实例 1 和 2 以完全相同的秒数和毫秒读取文件时,我收到一个异常,说文件正在被另一个进程使用。当实例 1 和 2 之间存在几毫秒的差异时,不会出现此锁定错误。

我尝试过的事情 1.尝试使用FileShare.ReadWrite参数,问题依旧。

  1. 试图在实例 1 和 2 之间造成一些延迟,但有时会出现问题。

  2. 尝试使用 using 语句来关闭 FileStream 对象,但问题仍然存在。

避免此问题的任何想法/建议。

代码片段

StreamReader sr = null;
FileStream fs = null;
try 
{
    fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    sr = new StreamReader(fs);
    while (sr.Peek() != -1)
    {
     // Does only read operations no write.
    }
    sr.Close();
    fs.Close();
}
catch (Exception Ex)
{
    try
    {
        if (sr != null)
            sr.Close();
        if (fs != null)
            fs.Close();
    }
    catch (Exception innerException)
    {

    }  
 }

【问题讨论】:

  • 我建议创建单个路由来读取文件并将内容与文件名一起作为标题放入队列中。然后您可以在该队列上进行并行处理

标签: c# .net c#-4.0 file-io


【解决方案1】:

一个想法是使用某种重试策略并将您的代码包装在try/catch 中。您还可以将 fssr 声明放在 using 语句中,这样您就不必担心对它们调用 Close

int retries = 3;

while (retries > 0)
{
    try
    {
        using (var fs = File.OpenRead(FileName))
        using (var sr = new StreamReader(fs))
        {
            while (sr.Peek() != -1)
            {
                // Does only read operations no write.
            }
        }

        break; // Exit the while loop if successful
    }
    catch
    {
        // Decrement our retry count and wait a bit if we're not done
        if (--retries > 0) Thread.Sleep(TimeSpan.FromSeconds(5));
    }
}

【讨论】:

    【解决方案2】:

    希望有人能给你一个更清晰的答案,但如果读取文件很关键,那么我可能会将其放入 try/catch 块中,如果由于锁定而失败,请等待几毫秒,然后再试一次.

    不幸的是,在具有大量磁盘活动的大型系统中,这种方法可能会损害性能,但在较小的系统中,它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2022-06-16
      • 2020-08-20
      • 2018-09-07
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多