多线程环境中的文件访问策略(Web App)

Rob*_*per 6 asp.net file-io multithreading caching web-applications

我有一个文件,它是从Web服务获取并在Web应用程序中本地缓存的某些数据的XML表示形式.我们的想法是,这些数据非常静态,但可能会发生变化.所以我已将其设置为缓存到文件,并对其进行监视,以检查它是否已被删除.删除后,文件将从其源代码刷新并重建.

我现在正在遇到问题,因为很明显在多线程环境中,当它仍然在读取/写入文件时试图访问数据时它会崩溃.

这让我感到困惑,因为我添加了一个要锁定的对象,并且在读/写期间总是被锁定.据我了解,从其他线程尝试访问将被告知"等待"直到锁被释放?

只是为了让你知道,我是多线程开发的新手,所以我完全愿意接受这是我的一个搞砸:)

  • 我错过了什么吗?
  • 多线程环境中最好的文件访问策略是什么?

编辑

对不起 - 我应该说这是使用ASP.NET 2.0 :)

Eri*_*ard 6

这是我用来确保文件未被其他进程锁定的代码.这不是100%万无一失,但它大部分时间都可以完成工作:

    /// <summary>
    /// Blocks until the file is not locked any more.
    /// </summary>
    /// <param name="fullPath"></param>
    bool WaitForFile(string fullPath)
    {
        int numTries = 0;
        while (true)
        {
            ++numTries;
            try
            {
                // Attempt to open the file exclusively.
                using (FileStream fs = new FileStream(fullPath,
                    FileMode.Open, FileAccess.ReadWrite, 
                    FileShare.None, 100))
                {
                    fs.ReadByte();

                    // If we got this far the file is ready
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.LogWarning(
                   "WaitForFile {0} failed to get an exclusive lock: {1}", 
                    fullPath, ex.ToString());

                if (numTries > 10)
                {
                    Log.LogWarning(
                        "WaitForFile {0} giving up after 10 tries", 
                        fullPath);
                    return false;
                }

                // Wait for the lock to be released
                System.Threading.Thread.Sleep(500);
            }
        }

        Log.LogTrace("WaitForFile {0} returning true after {1} tries",
            fullPath, numTries);
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

显然,您可以调整超时和重试以适合您的应用程序.我使用它来处理需要一段时间才能编写的大型FTP文件.