使用 SpinWait 實作檔案存取 Lock 機制

栏目: ASP.NET · 发布时间: 6年前

内容简介:今天在設計檔案 Lock 機制的時候,發現了一個好物多條執行續存取相同檔案時,基本要注意的事情如下:這邊我設計了一個

今天在設計檔案 Lock 機制的時候,發現了一個好物 SpinWait 可以用,比起  Thread.Sleep() + While(true) 更來的方便效能也較佳。

多條執行續存取相同檔案時,基本要注意的事情如下:

  1. 我讀取檔案時,允許他人讀取不允許寫入。
  2. 我寫入檔案時,不允許他人讀寫。

這邊我設計了一個 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 的問題發生。

參考: [C#.NET][Thread] 善用 SpinWait 處理 執行緒空轉 以利提昇效能


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Linux Device Drivers

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》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具