public void TryEnqueueAfterComplete()
 {
     var queue = new AsyncQueue<int>();
     Assert.True(queue.TryEnqueue(42));
     queue.Complete();
     Assert.False(queue.TryEnqueue(42));
 }
Ejemplo n.º 2
0
        public void TryEnqueueAfterComplete()
        {
            var queue = new AsyncQueue <int>();

            Assert.True(queue.TryEnqueue(42));
            queue.Complete();
            Assert.False(queue.TryEnqueue(42));
        }
Ejemplo n.º 3
0
 public void TryEnqueueAfterPromisingNotTo()
 {
     var queue = new AsyncQueue<int>();
     Assert.True(queue.TryEnqueue(42));
     queue.PromiseNotToEnqueue();
     Assert.Throws(typeof(InvalidOperationException), () => {
         queue.TryEnqueue(42);
     });
 }
Ejemplo n.º 4
0
        public void TryEnqueueAfterPromisingNotTo()
        {
            var queue = new AsyncQueue <int>();

            Assert.True(queue.TryEnqueue(42));
            queue.PromiseNotToEnqueue();
            Assert.Throws(typeof(InvalidOperationException), () => {
                queue.TryEnqueue(42);
            });
        }
Ejemplo n.º 5
0
        public Task <TResponseType> ExecuteAsync <TRequestType, TResponseType>(
            bool mutatesSolutionState,
            IRequestHandler <TRequestType, TResponseType> handler,
            TRequestType request,
            ClientCapabilities clientCapabilities,
            string?clientName,
            CancellationToken requestCancellationToken) where TRequestType : class
        {
            // Create a task completion source that will represent the processing of this request to the caller
            var completion = new TaskCompletionSource <TResponseType>();

            // Note: If the queue is not accepting any more items then TryEnqueue below will fail.

            var textDocument = handler.GetTextDocumentIdentifier(request);
            var item         = new QueueItem(mutatesSolutionState, clientCapabilities, clientName, textDocument,
                                             callbackAsync: async(context, cancellationToken) =>
            {
                // Check if cancellation was requested while this was waiting in the queue
                if (cancellationToken.IsCancellationRequested)
                {
                    completion.SetCanceled();

                    // Tell the queue to ignore any mutations from this request, not that we've given it a chance
                    // to make any
                    return(false);
                }

                try
                {
                    var result = await handler.HandleRequestAsync(request, context, cancellationToken).ConfigureAwait(false);
                    completion.SetResult(result);
                    // Tell the queue that this was successful so that mutations (if any) can be applied
                    return(true);
                }
                catch (OperationCanceledException ex)
                {
                    completion.TrySetCanceled(ex.CancellationToken);
                }
                catch (Exception exception)
                {
                    // Pass the exception to the task completion source, so the caller of the ExecuteAsync method can observe but
                    // don't let it escape from this callback, so it doesn't affect the queue processing.
                    completion.SetException(exception);
                }

                // Tell the queue to ignore any mutations from this request
                return(false);
            }, requestCancellationToken);

            var didEnqueue = _queue.TryEnqueue(item);

            // If the queue has been shut down the enqueue will fail, so we just fault the task immediately.
            // The queue itself is threadsafe (_queue.TryEnqueue and _queue.Complete use the same lock).
            if (!didEnqueue)
            {
                completion.SetException(new InvalidOperationException("Server was requested to shut down."));
            }

            return(completion.Task);
        }
Ejemplo n.º 6
0
        public async Task AsyncSendAndCloseAndReceiveAll(int count)
        {
            var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var asyncQueue   = new AsyncQueue <int>();

            var sendValue = 0;
            var sendTask  = new Func <Task>(async() =>
            {
                await Task.Yield();
                while (cancellation.IsCancellationRequested == false)
                {
                    if (asyncQueue.TryEnqueue(sendValue++) == false)
                    {
                        return;
                    }
                    await Task.Delay(10).ConfigureAwait(false);
                }
            })().IgnoreFaultOrCancellation().ConfigureAwait(false);

            await Task.Delay(count);

            var actualSum = asyncQueue.TakeAllAndClose().Sum();

            await sendTask;

            var expectedSum = Enumerable.Range(0, sendValue).Sum();

            Assert.NotEqual(expectedSum, actualSum);
            Assert.Equal(0, asyncQueue.Count);
            cancellation.Cancel();
        }
Ejemplo n.º 7
0
        public async Task ParallelSendAndDequeueAsync(int count)
        {
            var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var options      = new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount, TaskScheduler = TaskScheduler.Default
            };
            var asyncQueue  = new AsyncQueue <int>();
            var items       = Enumerable.Range(0, count).ToArray();
            var expectedSum = items.Sum();

            var actualSum   = 0;
            var ct          = 0;
            var receiveTask = new Func <Task>(async() =>
            {
                await Task.Yield();

                while (cancellation.IsCancellationRequested == false)
                {
                    var value = await asyncQueue.DequeueAsync(cancellation.Token).ConfigureAwait(false);

                    Interlocked.Add(ref actualSum, value);
                    if (Interlocked.Increment(ref ct) == count)
                    {
                        return;
                    }
                }
            })();

            Parallel.For(0, count, options, i => Assert.True(asyncQueue.TryEnqueue(i), "fail to send"));

            await receiveTask.ConfigureAwait(false);

            Assert.Equal(expectedSum, actualSum);
            Assert.Equal(0, asyncQueue.Count);
        }
Ejemplo n.º 8
0
        internal void CompleteCompilationEventQueue_NoLock()
        {
            Debug.Assert(EventQueue != null);

            // Signal the end of compilation.
            EventQueue.TryEnqueue(new CompilationCompletedEvent(this));
            EventQueue.PromiseNotToEnqueue();
            EventQueue.TryComplete();
        }
Ejemplo n.º 9
0
        public void QueueRepositoryDiscovery(string filePath)
        {
            lock (_filesRepositoryToDiscover)
            {
                Requires.NotNullOrEmpty(filePath, nameof(filePath));
                _filesRepositoryToDiscover.TryEnqueue(filePath);
            }

            TreatRepositoryDiscoveryQueueAsync().Forget();
        }
Ejemplo n.º 10
0
        public void TryEnqueueAndTryDequeue(int count)
        {
            var asyncQueue = new AsyncQueue <int>();

            for (var i = 0; i < count; i++)
            {
                Assert.True(asyncQueue.TryEnqueue(i), "fail to send");
            }

            for (var i = 0; i < count; i++)
            {
                var value = default(int);
                Assert.True(asyncQueue.TryDequeue(out value), "fail to receive");
                Assert.Equal(i, value);
            }

            Assert.Equal(0, asyncQueue.Count);
        }
Ejemplo n.º 11
0
        public async Task TryEnqueueAndDequeueAsync(int count)
        {
            var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(1000));
            var asyncQueue   = new AsyncQueue <int>();
            var items        = Enumerable.Range(0, count).ToArray();
            var expectedSum  = items.Sum();

            var actualSum   = 0;
            var ct          = 0;
            var receiveTask = new Func <Task>(async() =>
            {
                await Task.Yield();

                while (cancellation.IsCancellationRequested == false)
                {
                    var receiveValueTask = asyncQueue.DequeueAsync(cancellation.Token).ConfigureAwait(false);
                    var value1           = await receiveValueTask;
                    var value2           = await receiveValueTask;

                    Assert.Equal(value1, value2); // check if awaited values are same

                    this.logger.Debug(value1.ToString());
                    Interlocked.Add(ref actualSum, value1);
                    if (Interlocked.Increment(ref ct) == count)
                    {
                        return;
                    }
                }
            })();

            await Task.Delay(10, cancellation.Token).ConfigureAwait(false);

            for (var i = 0; i < count; i++)
            {
                Assert.True(asyncQueue.TryEnqueue(i), "fail to send");
            }

            await receiveTask.ConfigureAwait(false);

            Assert.Equal(expectedSum, actualSum);
            Assert.Equal(0, asyncQueue.Count);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Бесконечно запрашивает у пользователя сообщения для отправки
        /// </summary>
        static void AskingUserForMessages()
        {
            while (true)
            {
                Console.WriteLine("Введите сообщение для отправки на сервер: ");
                var messageText = Console.ReadLine();
                if (messageText == string.Empty)
                {
                    closeProgram = true;
                    break;
                }
                var newMessage = new Message()
                {
                    Text = messageText
                };

                SaveMessage(newMessage);
                messagesToSend.TryEnqueue(newMessage);
            }
        }
Ejemplo n.º 13
0
        public async Task SlowSendAndFastDequeueAsync(int seconds)
        {
            var cancellation  = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var asyncQueue    = new AsyncQueue <int>(10);
            var expectedValue = (int)(DateTime.Now.Ticks % int.MaxValue);

            var ct          = 0;
            var receiveTask = new Func <Task>(async() =>
            {
                await Task.Yield();

                while (cancellation.IsCancellationRequested == false)
                {
                    await Task.Delay(1).ConfigureAwait(false);
                    var actual = await asyncQueue.DequeueAsync(cancellation.Token).ConfigureAwait(false);
                    ct++;
                    Assert.Equal(expectedValue, actual);
                }
            })().IgnoreFaultOrCancellation().ConfigureAwait(false);

            var sendTask = new Func <Task>(async() =>
            {
                await Task.Yield();
                while (cancellation.IsCancellationRequested == false)
                {
                    asyncQueue.TryEnqueue(expectedValue);
                    await Task.Delay(2).ConfigureAwait(false);
                }
            })().IgnoreFaultOrCancellation().ConfigureAwait(false);

            while (cancellation.IsCancellationRequested == false)
            {
                await Task.Delay(10).ConfigureAwait(false);
            }

            await receiveTask;
            await sendTask;

            Assert.NotEqual(0, ct);
        }
Ejemplo n.º 14
0
        public void ParallelSendAndTryDequeue(int count)
        {
            var asyncQueue = new AsyncQueue <int>();
            var options    = new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount, TaskScheduler = TaskScheduler.Default
            };
            var items       = Enumerable.Range(0, count).ToArray();
            var expectedSum = items.Sum();

            Parallel.For(0, count, options, i => Assert.True(asyncQueue.TryEnqueue(i), "fail to send"));

            var actualSum = 0;
            var value     = default(int);

            while (asyncQueue.TryDequeue(out value))
            {
                actualSum += value;
            }

            Assert.Equal(expectedSum, actualSum);
            Assert.Equal(0, asyncQueue.Count);
        }
Ejemplo n.º 15
0
        public async Task ParallelSendAndCloseReceiveAll(int count)
        {
            var cancellationSource = new CancellationTokenSource();
            var asyncQueue         = new AsyncQueue <int>();
            var options            = new ParallelOptions {
                CancellationToken = cancellationSource.Token, MaxDegreeOfParallelism = Environment.ProcessorCount / 2, TaskScheduler = TaskScheduler.Default
            };
            var items = new ConcurrentQueue <int>(Enumerable.Range(0, count));

            var sendTask = Task.Factory.StartNew(() => Parallel.For(0, count, options, i =>
            {
                var item = default(int);
                if (items.TryDequeue(out item))
                {
                    if (asyncQueue.TryEnqueue(item) == false)
                    {
                        items.Enqueue(item);
                    }
                }
            }));

            await Task.Delay(1).ConfigureAwait(false);

            var itemsInAsyncQueue = asyncQueue.TakeAllAndClose(); // deny TryEnqueue

            cancellationSource.Cancel();                          // stop parallel for

            await sendTask.IgnoreFaultOrCancellation().ConfigureAwait(false);

            var actualCount = items.Count + itemsInAsyncQueue.Count;

            this.logger.Debug($"[TEST] en-queued: {itemsInAsyncQueue.Count}, total: {count}");

            Assert.Equal(count, actualCount);
            Assert.Equal(0, asyncQueue.Count);
        }
Ejemplo n.º 16
0
        private async Task NegotiateWebSocket(NetworkConnection networkConnection)
        {
            if (networkConnection == null)
            {
                throw new ArgumentNullException(nameof(networkConnection));
            }

            await Task.Yield();

            WebSocketNegotiationResult result;

            try
            {
                var timeoutTask = Task.Delay(_options.NegotiationTimeout);

                foreach (var conExt in _extensions)
                {
                    var extTask = conExt.ExtendConnectionAsync(networkConnection);
                    await Task.WhenAny(timeoutTask, extTask).ConfigureAwait(false);

                    if (timeoutTask.IsCompleted)
                    {
#pragma warning disable 4014
                        extTask.IgnoreFaultOrCancellation(); // make connection exception observed
#pragma warning restore 4014
                        throw new WebSocketException($"Negotiation timeout (Extension: {conExt.GetType().Name})");
                    }

                    networkConnection = await extTask.ConfigureAwait(false);
                }

                var handshakeTask = _handShaker.HandshakeAsync(networkConnection);
                await Task.WhenAny(timeoutTask, handshakeTask).ConfigureAwait(false);

                if (timeoutTask.IsCompleted)
                {
#pragma warning disable 4014
                    handshakeTask.IgnoreFaultOrCancellation(); // make connection exception observed
#pragma warning restore 4014
                    throw new WebSocketException("Negotiation timeout");
                }

                var handshake = await handshakeTask.ConfigureAwait(false);

                if (handshake.IsValidWebSocketRequest)
                {
                    result = new WebSocketNegotiationResult(handshake.Factory.CreateWebSocket(networkConnection, _options, handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions));
                }
                else if (handshake.IsValidHttpRequest && _options.HttpFallback != null)
                {
                    _options.HttpFallback.Post(handshake.Request, networkConnection);
                    return;
                }
                else
                {
                    SafeEnd.Dispose(networkConnection, this.log);
                    result = new WebSocketNegotiationResult(handshake.Error);
                }

                var webSocket = result.Result;
                if (_negotiations.TryEnqueue(result) == false)
                {
                    SafeEnd.Dispose(webSocket);
                    return; // too many negotiations
                }

                if (webSocket != null)
                {
                    this.pingQueue?.GetSubscriptionList().Add(webSocket);
                }
            }
            catch (Exception negotiationError)
            {
                if (this.log.IsDebugEnabled)
                {
                    this.log.Debug("An error occurred while negotiating WebSocket request.", negotiationError);
                }

                SafeEnd.Dispose(networkConnection, this.log);
                result = new WebSocketNegotiationResult(ExceptionDispatchInfo.Capture(negotiationError));
            }
            finally
            {
                _semaphore.Release();
            }
        }