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

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

内容简介:今天在設計檔案 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 處理 執行緒空轉 以利提昇效能


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

查看所有标签

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

The Web Designer's Idea Book

The Web Designer's Idea Book

Patrick Mcneil / How / 2008-10-6 / USD 25.00

The Web Designer's Idea Book includes more than 700 websites arranged thematically, so you can find inspiration for layout, color, style and more. Author Patrick McNeil has cataloged more than 5,000 s......一起来看看 《The Web Designer's Idea Book》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具