<分区>
我正在尝试提供一种锁定全局资源的解决方案,该方式要求锁定访问权限并且可用于同步或异步操作。
我创建了一个通用类 State:
public class State<T>
{
public class LockedState : IDisposable {
public LockedState(State<T> state) { this.state = state; Monitor.Enter(this.state.theLock); } // would be great if this could be private
public void Dispose() => Monitor.Exit(this.state.theLock);
public ref T Val { get { return ref state.t; } }
readonly State<T> state;
};
public State() { }
public State(T t) { this.t = t; }
public LockedState Locked { get { return new LockedState(this); } }
readonly object theLock = new object();
T t;
}
这里的想法是我可以在 Program 类中拥有一个全局“商店”:
public class Program {
static public readonly State<ImmutableList<int>> TheList = new State<ImmutableList<int>>(ImmutableList<int>.Empty);
static public readonly State<SomeType> SomeType = new State<SomeType>(SomeType());
}
然后访问状态的唯一方法是像这样获取锁:
using (var lTheList = Program.TheList.Locked) {
lTheList.Val = lTheList.Val.Add(5));
}
在我的例子中,它比普通锁工作得更好,因为它在获取/设置之前强制锁定(你不能忘记锁定)
(旁注这是一个好策略吗?)
问题是我不能在异步代码中使用上面的内容:
using (var someType = Program.SomeType.Lock()) {
var x = await someType.Val.SomeAsyncOp();
}
我得到一个异常:从未同步的代码块调用了对象同步方法
我找到了这篇文章 How to protect resources that may be used in a multi-threaded or async environment?它有一个 AsyncLock 类但是我不明白如何将 AsyncLock 这样的类放入我的 StateLock 类中..
State.Lock()
能否返回可用于同步和异步调用方的锁定状态?这正是我要找的!
如果不是,我最好的前进方向是什么?使用 SemaphoreSlim
并使用 State.Lock()
和 State.AsyncLock()
?
谢谢!