public AsyncReaderWriterLock()
        {
            _readerTail = new ReaderLockSource(this);
            _writerTail = new WriterLockSource(this);

            _readerTail.CompleteTasks();
            _writerTail.TryCompleteTask();
            _writerTail.Task.Result.Dispose();
        }
        private void CompleteNextTask(WriterLockSource writer)
        {
            var reader = _readerTail;

            while (writer != null && !writer.TryCompleteTask())
            {
                writer = writer.NextWriter;
            }

            // No writer source left - complete reader source tasks
            if (writer == null)
            {
                reader.CompleteTasks();
            }
        }
            public void RegisterWait(WriterLockSource writer, CancellationToken cancellationToken)
            {
                Interlocked.Exchange(ref _writer, writer);

                CompleteTasks();

                if (cancellationToken.IsCancellationRequested)
                {
                    CancelWaitReaders(cancellationToken);
                }
                else if (_count == 0)
                {
                    writer.TryCompleteTask();
                }
                else if (cancellationToken.CanBeCanceled)
                {
                    cancellationToken.Register(CancelWaitReaders, cancellationToken, false);
                }
            }