文件访问策略在多线程环境(Web应用程序) [英] File Access Strategy in a Multi-Threaded Environment (Web App)
问题描述
我有一个文件,它是从一个Web服务,并采取本地缓存Web应用程序中的某些数据的XML重新presentation。这个想法是是,此数据的非常的静态,只是可能的变化。所以我将它设置缓存到一个文件中,并坚持显示器反对,以检查它是否已被删除。一旦删除,该文件将其源刷新和重建。
I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is very static, but just might change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt.
我现在的问题在运行但是,因为很明显的,因为它正试图访问时,它仍然是读取/写入文件中的数据它属于在一个多线程环境。
I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file.
这是混淆了我,因为我添加了一个对象锁定反对,这是读/写过程中始终处于锁定状态。这是我的理解是试图从其它线程访问会被告知要等待直到锁被释放?
This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released?
只是为了让你知道,我是真正的新多线程开发,所以我完全愿意接受,这是一个螺丝钉在我的部分:)
Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part :)
- 我缺少的东西吗
- 什么是在多线程环境最好的文件访问策略?
对不起 - 我应该说这是使用的 ASP.NET 2.0 :)
Sorry - I should have said this is using ASP.NET 2.0 :)
推荐答案
下面是我用它来确保文件不会被其他进程锁定了code。这不是100%的万无一失,但它能够完成大部分时间工作:
Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time:
/// <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文件。
Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.
这篇关于文件访问策略在多线程环境(Web应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!