gpt4 book ai didi

asp.net - 多线程环境下的文件访问策略(Web App)

转载 作者:行者123 更新时间:2023-12-02 12:44:33 25 4
gpt4 key购买 nike

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

我现在遇到了问题,因为显然在多线程环境中它会崩溃,因为它仍在读取/写入文件时尝试访问数据。

这让我很困惑,因为我添加了一个要锁定的对象,并且该对象在读/写期间始终处于锁定状态。据我了解,尝试从其他线程进行访问时会被告知“等待”直到锁被释放?

只是想让你知道,我对多线程开发真的很陌生,所以我完全愿意接受这是我的一个错误:)

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

编辑

抱歉 - 我应该说这是使用 ASP.NET 2.0 :)

最佳答案

这是我用来确保文件不被另一个进程锁定的代码。它不是 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;
}

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

关于asp.net - 多线程环境下的文件访问策略(Web App),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com