public void TestDoubleRelease() { using (AsyncLocker locker = new AsyncLocker()) { using (LockReleaser l = locker.Lock()) { l.Dispose(); } } }
public static async Task DoubleCheckAndDoAsync(this AsyncLocker locker, Func <bool> condition, Func <Task> action) { if (condition() && action != null) { using (await locker.LockAsync()) { if (condition()) { await action().DonotCapture(); } } } }
public static void DoubleCheckAndDo(this AsyncLocker locker, Func <bool> condition, Action action) { if (condition() && action != null) { using (locker.Lock()) { if (condition()) { action(); } } } }
public void TestTimeoutAsync() { Assert.ThrowsAsync <TimeoutException>(async() => { using (AsyncLocker locker = new AsyncLocker()) { Task[] tasks = Enumerable.Range(0, 2).Select(x => Task.Run(async() => { using (await locker.LockAsync(TimeSpan.FromSeconds(0.1))) { await Task.Delay(TimeSpan.FromSeconds(1)); } })).ToArray(); await Task.WhenAll(tasks); } }); }
public async Task TestThreadSafe() { SyncChecker syncChecker = new SyncChecker(); using (AsyncLocker locker = new AsyncLocker()) { Task[] tasks = Enumerable.Range(0, 2).Select(x => Task.Run(async() => { using (locker.Lock()) { syncChecker.Enter(); await Task.Delay(TimeSpan.FromSeconds(1)); syncChecker.Leave(); } })).ToArray(); await Task.WhenAll(tasks); } }
public void TestCancellationToken() { Assert.ThrowsAsync <OperationCanceledException>(async() => { using (AsyncLocker locker = new AsyncLocker()) { Task[] tasks = Enumerable.Range(0, 2).Select(x => Task.Run(async() => { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(0.1)); using (locker.Lock(cancellationTokenSource.Token)) { await Task.Delay(TimeSpan.FromSeconds(1)); } })).ToArray(); await Task.WhenAll(tasks); } }); }
void OnLocked(object state, bool timedout) { AsyncLocker al = (AsyncLocker)state; al.Callback(al.State, timedout); }