内容简介:今天在設計檔案 Lock 機制的時候,發現了一個好物多條執行續存取相同檔案時,基本要注意的事情如下:這邊我設計了一個
今天在設計檔案 Lock 機制的時候,發現了一個好物 SpinWait
可以用,比起 Thread.Sleep()
+ While(true)
更來的方便效能也較佳。
多條執行續存取相同檔案時,基本要注意的事情如下:
- 我讀取檔案時,允許他人讀取不允許寫入。
- 我寫入檔案時,不允許他人讀寫。
這邊我設計了一個 FileHandler
來處理這件事情,程式碼如下:
public class FileHandler
{
public void WriteFileContent(string content)
{
using (var fs = waitFileForUse(FileAccess.Write, FileShare.None))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.Write(content);
}
}
}
public string ReadFileContent()
{
using (var fs = waitFileForUse(FileAccess.Read, FileShare.Read))
{
using (var sr = new StreamReader(fs, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
}
private FileStream waitFileForUse(FileAccess fileAccess, FileShare fileShare)
{
const int maxRetryMilliseconds = 5 * 1000;
string filePath = "note.json";
FileStream fs = null;
SpinWait.SpinUntil(() =>
{
try
{
fs = new FileStream(filePath, FileMode.OpenOrCreate, fileAccess, fileShare);
}
catch { }
return (fs != null);
}, maxRetryMilliseconds);
if (fs == null)
{
throw new IOException($"無法開啟 {filePath}, 已超過 {maxRetryMilliseconds} ms 重試上限");
}
return fs;
}
}
waitFileForUse
這個 Method 裡面我使用了 SpinWait
來去判斷檔案是否可以存取,並設定 Timeout 秒數避免 Deadlock 的問題發生。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- ECMAScript 之 Object Property 存取
- matlab—特殊变量类型与档案存取
- CHAR 和 VARCHAR 存取的差别
- Yii授权之基于角色的存取控制 (RBAC)
- iOS汇编入门教程(三)汇编中的 Section 与数据存取
- 【茶包射手日記】Windows Server 2016 網路分享無法遠端存取
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Linux Device Drivers
Jonathan Corbet、Alessandro Rubini、Greg Kroah-Hartman / O'Reilly Media / 2005-2-17 / USD 39.95
Device drivers literally drive everything you're interested in--disks, monitors, keyboards, modems--everything outside the computer chip and memory. And writing device drivers is one of the few areas ......一起来看看 《Linux Device Drivers》 这本书的介绍吧!