gpt4 book ai didi

c# - 读取/写入文件 : heavily used application 的正确方法

转载 作者:行者123 更新时间:2023-11-30 22:29:36 25 4
gpt4 key购买 nike

我们有一个经常使用的 .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;
}

最佳答案

您可以在其上添加一个全局互斥量,以避免不必要的等待。

全局互斥是通过传递一个非空的nameMutex Constructor来创建的.

好处:

  • Mutex 将允许您在文件可用后立即唤醒,而不是平均等待 50 毫秒。
  • Mutex 允许您一次休眠并一次醒来,而不是反复 sleep /醒来。操作系统可以非常高效地处理休眠线程,几乎不消耗任何资源。
  • 一旦获得互斥量,文件打开几乎 100% 可能成功,而不是在成功之前可能失败很多次。

总而言之,您不仅会变得更快,而且您可能会在此过程中消耗更少的 CPU 周期

关于c# - 读取/写入文件 : heavily used application 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10147055/

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