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作為構造函數進行更改。