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中文网其他相关文章!