我们有一个大量使用的 .Net 3.5 应用程序,它读取“创建成本高”的数据并将其缓存。应用程序基于它而不是“被另一个进程使用”来读取\写入文件。如果其他进程正在读取和写入文件,则应用程序进入睡眠状态(一段时间)并重试。这是读写文件的正确方法吗?请指教。
public void Add<T>(string key, CacheItem<T> item)
{
bool fileInUse = false;
while (!fileInUse)
{
try
{
using (Stream stream = new FileStream(Path.Combine(cachePath, key+".bin"), FileMode.Create, FileAccess.Write, FileShare.None))
{
Serializer.NonGeneric.Serialize(stream, item);
}
fileInUse = true;
}
catch (IOException ex)
{
if (ex.Message.Contains("being used by another process"))
{
//Poll till the file is free to be used by this process
Thread.Sleep(100);
fileInUse = false;
}
}
}
}
public CacheItem<T> Get<T>(string key, Type type)
{
CacheItem<T> item = null;
FileInfo fileInfo = new FileInfo(Path.Combine(cachePath, key+".bin"));
fileInfo.Refresh();
if (fileInfo.Exists)
{
bool fileInUse = false;
while (!fileInUse)
{
try
{
using (Stream stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.None))
{
object objectTemp = Serializer.NonGeneric.Deserialize(type, stream);
item = (CacheItem<T>)objectTemp;
}
fileInUse = true;
}
catch(IOException ex)
{
if (ex.Message.Contains("being used by another process"))
{
//Poll till the file is free to be used by this process
Thread.Sleep(100);
fileInUse = false;
}
}
}
}
return item;
}