Beispiel #1
0
 public void Close()
 {
     _cts?.Cancel();
     _cts?.Dispose();
     _channel?.Writer.Complete();
     try
     {
         _udp.Close();
     }
     catch { }
 }
Beispiel #2
0
        public async ValueTask ConnectAsync(Uri url, CancellationToken token)
        {
            ThrowIfDisposed();

            _limboCts?.Cancel();
            _limboCts?.Dispose();
            _limboCts = new Cts();
            _ws?.Dispose();
            _ws = _webSocketClientFactory.CreateClient();
            if (_supportsZLib)
            {
                _receiveZLibStream?.Dispose();
                _receiveZLibStream = _createZLibStream(_receiveStream);
            }
            await _ws.ConnectAsync(url, token).ConfigureAwait(false);
        }
Beispiel #3
0
        private async void OnSearchTextChangedEvent(object sender, EventArgs e, object paramaters)
        {
            var model = (CustomerManagementPageViewModel)ParentsModel;

            if (model.IsDataGridLoading)
            {
                if (Cts != null)
                {
                    Cts.Cancel();
                }
            }

            model.IsDataGridLoading = true;
            if (customerDGCache == null)
            {
                customerDGCache = (DataGrid)((object[])paramaters)[0];
            }
            TextBox ctrl = (TextBox)sender;

            await Task.Delay(100);

            if (Cts == null)
            {
                Cts = new CancellationTokenSource();
            }

            var ct = Cts.Token;

            try
            {
                await Task.Delay(model.DelayTextChangedHandler, ct);

                customerDGCache.Items.Filter = new Predicate <object>(customer => FilterCustomerList(customer as tblCustomer, ctrl.Text));
                model.IsDataGridLoading      = false;
            }
            catch (OperationCanceledException ex)
            {
                if (Cts != null)
                {
                    Cts.Dispose();
                }
                Cts = null;
            }
        }
    public async Task ShouldCancelWaiting(SemaphoreSlimLock sut)
    {
        var mutex = GetSemaphore(sut);
        await sut.WaitAsync(Cts.Token);

        var second = sut.WaitAsync(Cts.Token);

        await Wait();

        Assert.False(second.IsCompleted);
        Assert.Equal(0, mutex.CurrentCount);

        Cts.Cancel();
        await AssertThrowsAsync <OperationCanceledException>(
            () => second);

        Assert.True(second.IsCanceled);
        Assert.Equal(0, mutex.CurrentCount);
    }
        public async Task ShouldWaitForMessageUntilCanceled(
            [Frozen] Mock <IConnectionInitializer> initializer,
            ConnectionHandler sut)
        {
            var connection = new TestConnection();

            initializer.Setup(x => x.ConnectAsync(connection, Cts.Token))
            .ReturnsAsync(Create <ConnectedClient>(
                              new ClientWithConnectionBuilder(connection)));

            var result = sut.HandleAsync(connection, Cts.Token);

            await Wait();

            Assert.False(result.IsCompleted);

            Cts.Cancel();
            await Assert.ThrowsAsync <OperationCanceledException>(() => result);
        }
            private void GenerateNumbers()
            {
                CancellationToken token = Cts.Token;

                try
                {
                    Console.WriteLine("Start generating numbers");
                    for (int i = 0; i < BUFFER_SIZE; i++)
                    {
                        if (token.IsCancellationRequested)
                        {
                            break;
                        }

                        decimal percent = ((i / (decimal)BUFFER_SIZE) * 100);
                        if (percent % 1 == 0)
                        {
                            Console.WriteLine("    Generating " + (int)percent + "%");
                        }

                        int i2 = i;
                        Output.Add(new SeqObject <int>()
                        {
                            SeqId = i2, Value = i2
                        }, token);
                    }
                    Console.WriteLine("Finished generating numbers");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Generating numbers failed");
                    if (!(ex is OperationCanceledException))
                    {
                        Cts.Cancel();
                        throw;
                    }
                }
                finally
                {
                    Output.CompleteAdding();
                }
            }
Beispiel #7
0
 private void BtnStop_Click(object sender, EventArgs e)
 {
     mrEvent.Set(); // Если останавливаем с паузы
     Cts.Cancel();
     timer.Stop();
     CurrentState.IsPauseEnabled      = false;
     CurrentState.IsStartEnabled      = true;
     CurrentState.IsStopEnabled       = false;
     CurrentState.IsOpenFolderEnabled = true;
     if (t.Status == TaskStatus.Running)
     {
         Task t2 = t.ContinueWith((t) => CurrentState.SetDefault(mainDispatcher));
     }
     else
     {
         CurrentState.SetDefault(mainDispatcher);
         tvFilesFound.Nodes.Clear();
     }
     mrEvent.Reset();
     timer.Dispose();
 }
        public void Dispose()
        {
            Cts.Cancel();
            TcpListener?.Stop();

            if (_hotTasks != null)
            {
                lock (_lock)
                {
                    _hotTasks.Clear();
                }
            }

            if (_clients != null)
            {
                foreach (var c in _clients)
                {
                    c.Dispose();
                }
            }
        }
Beispiel #9
0
        public async ValueTask ConnectAsync(Uri url, CancellationToken token)
        {
            ThrowIfDisposed();

            _limboCts?.Cancel();
            _limboCts?.Dispose();
            _limboCts = new Cts();
            _ws?.Dispose();
            _ws = _webSocketClientFactory.CreateClient();
            if (_supportsZLib)
            {
                _receiveZLibStream?.Dispose();
                _receiveZLibStream =
#if NET5_0
                    CreateZLibStream(_receiveStream);
#else
                    new ZLibStream(_receiveStream, CompressionMode.Decompress, true);
#endif
            }

            await _ws.ConnectAsync(url, token).ConfigureAwait(false);
        }
Beispiel #10
0
 public virtual void Stop()
 {
     try
     {
         ThrowIfDisposed();
         lock (lockable)
         {
             if (State == AgentState.Running)
             {
                 State = AgentState.StopRequested;
                 Cts.Cancel();
                 State = AgentState.Stopped;
             }
         }
     }
     catch (Exception exc)
     {
         // ignore. Just make sure stop does not throw.
         Log.Debug("Ignoring error during Stop: {0}", exc);
     }
     Log.Debug("Stopped agent");
 }
Beispiel #11
0
    public async Task WhenAll_ShouldCancel(bool isAsynchronous)
    {
        var canceled1 = new ValueTask(Task.FromCanceled(new CancellationToken(true)));
        var canceled2 = new ValueTask(Task.FromCanceled(new CancellationToken(true)));
        var running1  = new ValueTask(Task.Delay(Timeout.Infinite, Cts.Token));
        var running2  = new ValueTask(Task.Delay(Timeout.Infinite, Cts.Token));

        var result = isAsynchronous
            ? AsyncHelpers.WhenAll(new[] { canceled1, running1, running2 })
            : AsyncHelpers.WhenAll(new[] { canceled1, canceled2 });

        if (isAsynchronous)
        {
            await Wait();

            Assert.False(result.IsCompleted);
            Cts.Cancel();
        }

        await AssertThrowsAsync <TaskCanceledException>(() => result);

        Assert.True(result.IsCanceled);
    }
Beispiel #12
0
        public async Task ShouldCancelOnReceive()
        {
            var waiting = _sut.ReceiveAsync(Cts.Token);

            await Wait();

            Assert.False(waiting.IsCompleted);
            Assert.Equal(TestLock.State.Started, _receiveLock.WaitState);
            Assert.Equal(TestLock.State.None, _receiveLock.ReleaseState);
            Assert.Equal(TestLock.State.None, _sendLock.WaitState);
            Assert.Equal(TestLock.State.None, _sendLock.ReleaseState);
            _connection.Verify(x => x.ReceiveAsync(Cts.Token), Times.Never);

            Cts.Cancel();
            await Wait();

            Assert.True(waiting.IsCanceled);
            Assert.Equal(TestLock.State.Canceled, _receiveLock.WaitState);
            Assert.Equal(TestLock.State.None, _receiveLock.ReleaseState);
            Assert.Equal(TestLock.State.None, _sendLock.WaitState);
            Assert.Equal(TestLock.State.None, _sendLock.ReleaseState);
            _connection.Verify(x => x.ReceiveAsync(Cts.Token), Times.Never);
        }
Beispiel #13
0
        /// <summary>
        /// This method is used to cancel the task.
        /// </summary>
        public void Cancel()
        {
            if (IsCancelled)
            {
                return;
            }

            CancelledTime = DateTime.UtcNow;
            IsCancelled   = true;

            Cts.Cancel();

            try
            {
                if (Callback != null && !string.IsNullOrEmpty(CallbackId))
                {
                    Callback.TimeoutTaskManager(CallbackId);
                }
            }
            catch (Exception)
            {
            }
        }
            public void Reset()
            {
                lock (this)
                {
                    _resetCts?.Cancel();
                    _resetCts?.Dispose();

                    var currentCount = _semaphore.CurrentCount;
                    var releaseCount = _limit - currentCount;
                    try
                    {
                        if (releaseCount != 0)
                        {
                            _semaphore.Release(releaseCount);
                            _logger.LogDebug("Reset the semaphore: {0} -> {1}.", currentCount, _limit);
                        }
                    }
                    finally
                    {
                        _isResetting = false;
                    }
                }
            }
Beispiel #15
0
    public async Task ShouldUnsubscribeAfterCancellation(
        [Frozen] Notificator notificator,
        NotificatorConnection sut)
    {
        int GetSubscriptionCount()
        {
            return((typeof(Notificator)
                    .GetField(nameof(Notificator.Received), BindingFlags.Instance | BindingFlags.NonPublic)?
                    .GetValue(notificator) as Action)?.GetInvocationList()?.Length ?? 0);
        }

        Assert.Equal(0, GetSubscriptionCount());

        var result = sut.ReceiveAsync(Cts.Token);

        await Wait();

        Assert.Equal(1, GetSubscriptionCount());

        Cts.Cancel();
        await SwallowAnyAsync(result.AsTask());

        Assert.Equal(0, GetSubscriptionCount());
    }
 public void Stop( )
 {
     Logger.Info("Stopping Bot");
     fiatMonitor?.Stop( );
     Cts?.Cancel( );
 }
Beispiel #17
0
 public Task <ActionResult> ShutdownAsync()
 => Ok($"Goodbye! {DiscordHelper.Wave}", async _ =>
 {
     await Task.Yield();
     Cts.Cancel();
 });
Beispiel #18
0
 public override void Cancel()
 {
     Cts.Cancel();
 }
Beispiel #19
0
 public void CancelAsync()
 {
     Cts?.Cancel(false);
 }
Beispiel #20
0
 public ValueTask CloseAsync(CancellationToken cancellationToken = default)
 {
     _cts?.Cancel();
     _cts?.Dispose();
     _socket.Close();
     return(default);
Beispiel #21
0
 void ICommand.Execute(object parameter)
 {
     Cts.Cancel();
     RaiseCanExecuteChanged();
 }
Beispiel #22
0
 public Task <ActionResult> ShutdownAsync()
 => Ok($"Goodbye! {EmojiService.Wave}", _ =>
 {
     Cts.Cancel();
     return(Task.CompletedTask);
 });
Beispiel #23
0
 /// <summary>
 /// <para>
 /// Cancels the thread by calling Cancel on the CancellationTokenSource.  The value should be checked in the code in the specified Action parameter.
 /// </para>
 /// </summary>
 public virtual void Cancel()
 {
     Cts.Cancel();
 }
Beispiel #24
0
 private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
 {
     Info("Ctrl-C pressed. Exiting.");
     Cts.Cancel();
     Exit(ExitResult.SUCCESS);
 }
Beispiel #25
0
 /// <inheritdoc/>
 public void Dispose()
 {
     _cts.Cancel();
     _cts.Dispose();
 }
Beispiel #26
0
 public async Task ParseAsync()
 {
     await Task.Factory.StartNew(Parse).ContinueWith((x) => Cts.Cancel());
 }
Beispiel #27
0
 public void Dispose()
 {
     Cts.Cancel();
     Cts.Dispose();
 }
Beispiel #28
0
 /// <inheritdoc/>
 public void Dispose()
 {
     _cts.Cancel();
     _cts.Dispose();
     GC.SuppressFinalize(this);
 }
Beispiel #29
0
 /// <summary>
 /// 停止或暂停下载
 /// </summary>
 public void CancelAsync()
 {
     Package.Status = DownloadStatus.Pause;
     Cts?.Cancel(false);
 }
 /// <inheritdoc/>
 public virtual void Dispose()
 {
     _cts?.Cancel();
     _cts?.Dispose();
 }