public Task WaitAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); lock (_lockObj) { if (_currentCount > 0) { --_currentCount; return(Task.CompletedTask); } else { var task = new TaskNode(); if (_head == null) { _head = _tail = task; } else { _tail.Next = task; _tail = task; } if (cancellationToken != CancellationToken.None) { task.Cancellation = cancellationToken.Register(() => { task.TrySetCanceled(); if (task.Cancellation != default(CancellationTokenRegistration)) { task.Cancellation.Dispose(); } }); } return(task.Task); } } }