KeyLocks
1.0.0
基于不同对象类型(例如字符串,数字和日期)运行锁定代码。
有选择地将代码锁定在特定值上,而不是所有执行代码的代码。
private static KeyLock<string> _keyLock = new KeyLock<string>();
public void Main()
{
Parallel.Invoke(
() => { UpdateData("entity-123", "First new value"); },
() => { UpdateData("entity-123", "Second new value"); }, // This will await line above
() => { UpdateData("another-entity-456", "Another new value"); },
() => { UpdateData("yet-another-entity-789", "Yet another new value"); });
}
private void UpdateData(string id, string value)
{
_keyLock.RunWithLock(id, () =>
{
// Execute locked code
});
}
在Parallel.Invoke内部执行的方法1和2执行UpdateData - 方法,将等待彼此而不是同时运行,而所有其他方法都会并行运行。
NameLock类型是KeyLock<string>的短期任期。
它默认为对病例敏感的,但是可以通过将StringComparer.InvariantCultureIgnoreCase作为构造函数进行更改。