ImageProcessor 庫最近在快取更新期間遇到間歇性檔案存取錯誤,這是由於有缺陷的非同步鎖定造成的。本文分析了最初的錯誤實現並提供了一個可靠的解決方案。
原始方法使用雜湊 URL 作為非同步鎖定的金鑰,將 SemaphoreSlim
實例儲存在 ConcurrentDictionary
中以確保單鍵鎖定。 關鍵缺陷在於在SemaphoreSlim
釋放信號量之前從字典中同步刪除。這種競爭條件導致文件存取衝突。
以下程式碼片段說明了有問題的鍵/SemaphoreSlim
引用:
<code class="language-csharp">private static readonly Dictionary<object, RefCounted<SemaphoreSlim>> SemaphoreSlims = new Dictionary<object, RefCounted<SemaphoreSlim>>(); private SemaphoreSlim GetOrCreate(object key) { RefCounted<SemaphoreSlim> item; lock (SemaphoreSlims) { if (SemaphoreSlims.TryGetValue(key, out item)) { ++item.RefCount; } else { item = new RefCounted<SemaphoreSlim>(new SemaphoreSlim(1, 1)); SemaphoreSlims[key] = item; } } return item.Value; }</code>
下面是更正後的AsyncDuplicateLock
類,解決了並發問題:
<code class="language-csharp">public sealed class AsyncDuplicateLock { private sealed class RefCounted<T> { public RefCounted(T value) { RefCount = 1; Value = value; } public int RefCount { get; set; } public T Value { get; private set; } } private static readonly Dictionary<object, RefCounted<SemaphoreSlim>> SemaphoreSlims = new Dictionary<object, RefCounted<SemaphoreSlim>>(); private SemaphoreSlim GetOrCreate(object key) { RefCounted<SemaphoreSlim> item; lock (SemaphoreSlims) { if (SemaphoreSlims.TryGetValue(key, out item)) { ++item.RefCount; } else { item = new RefCounted<SemaphoreSlim>(new SemaphoreSlim(1, 1)); SemaphoreSlims[key] = item; } } return item.Value; } public IDisposable Lock(object key) { GetOrCreate(key).Wait(); return new Releaser { Key = key }; } public async Task<IDisposable> LockAsync(object key) { await GetOrCreate(key).WaitAsync().ConfigureAwait(false); return new Releaser { Key = key }; } private sealed class Releaser : IDisposable { public object Key { get; set; } public void Dispose() { RefCounted<SemaphoreSlim> item; lock (SemaphoreSlims) { item = SemaphoreSlims[Key]; --item.RefCount; if (item.RefCount == 0) SemaphoreSlims.Remove(Key); } item.Value.Release(); } } }</code>
此修訂後的實現確保信號量在從字典中刪除之前被釋放,消除了競爭條件並解決了間歇性文件存取錯誤。
以上是如何使用SemaphoreSlim正確實現非同步鎖定,防止間歇性檔案存取錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!