我們有一個使用頻率很高的.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;
}
您能否對上述代碼進行必要的更改? – Pankaj 2012-04-13 19:28:40
@PankajGarg我相信我可以,但那會完成什麼?關於這種機制如何運作,有什麼不清楚的地方嗎? – 2012-04-13 19:32:01
Branko; 下面是我們的一位架構師的狀態=>「我使用Mutex類的保留意見是,它的計算成本比使用鎖定語句或監視器類的計算成本要高得多,這不利於我們性能增強的目的。」有什麼想法嗎? – 2012-04-13 21:38:08