Exemplo n.º 1
0
        public async ValueTask SendAsync(Memory <byte> memory, CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                // See _limboCts for more info on cancellation.
                var sendTask = _ws.SendAsync(memory, WebSocketMessageType.Text, true, _limboCts.Token).AsTask();
                using (var infiniteCts = Cts.Linked(cancellationToken))
                {
                    var infiniteTask = Task.Delay(Timeout.Infinite, infiniteCts.Token);
                    var task         = await Task.WhenAny(infiniteTask, sendTask).ConfigureAwait(false);

                    infiniteCts.Cancel();
                }

                cancellationToken.ThrowIfCancellationRequested();
            }
            finally
            {
                _sendSemaphore.Release();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Stops the engine, exiting all currently running states
        /// </summary>
        public void Stop()
        {
            if (!_workerThread.IsBusy)
            {
                // If we're not running there's nothing to do.
                return;
            }

            if (_workerThread.IsBusy)
            {
                // Cancel our token source as to quickly exit any loops.
                Cts.Cancel();

                // End all the loaded states.
                foreach (State state in States)
                {
                    if (state.IsRunning)
                    {
                        state.Exit();
                    }
                }
            }
            // Stop the worker thread.
            _workerThread.CancelAsync();
        }
Exemplo n.º 3
0
        internal void CheckForLongTurns()
        {
            if (!IsFrozen())
            {
                return;
            }

            // Since this thread is running a long turn, which (we hope) is blocked on some IO
            // or other external process, we'll create a replacement thread and tell this thread to
            // exit when it's done with the turn.
            // Note that we only do this if the current load is reasonably low and the current thread
            // count is reasonably small.
            if (!pool.ShouldInjectWorkerThread ||
                !(this.performanceMetrics.CpuUsage < MAX_CPU_USAGE_TO_REPLACE))
            {
                return;
            }

            if (Cts.IsCancellationRequested)
            {
                return;
            }

            // only create a new thread once per slow thread!
            Log.Warn(ErrorCode.SchedulerTurnTooLong2, string.Format(
                         "Worker pool thread {0} (ManagedThreadId={1}) has been busy for long time: {2}; creating a new worker thread",
                         Name, ManagedThreadId, GetThreadStatus(true)));
            Cts.Cancel();
            pool.CreateNewThread();
            // Consider: mark the activation running a long turn to reduce it's time quantum
        }
Exemplo n.º 4
0
        public virtual void Stop()
        {
            try
            {
                ThrowIfDisposed();
                lock (lockable)
                {
                    if (State == AgentState.Running)
                    {
                        State = AgentState.StopRequested;
                        Cts.Cancel();
                        State = AgentState.Stopped;
                    }
                }
            }
            catch (Exception exc)
            {
                if (Log.IsEnabled(LogLevel.Debug))
                {
                    // ignore. Just make sure stop does not throw.
                    Log.LogDebug(exc, "Ignoring error during Stop");
                }
            }

            if (Log.IsEnabled(LogLevel.Debug))
            {
                Log.LogDebug("Stopped agent");
            }
        }
Exemplo n.º 5
0
 private void CancelAll()
 {
     Cts.Cancel();
     Cts.Dispose();
     Cts = new CancellationTokenSource();
     ActiveDownloads.Clear();
 }
Exemplo n.º 6
0
 public void Connect(string hostname, int port)
 {
     _udp.Connect(hostname, port);
     _cts     = new Cts();
     _channel = Channel.CreateUnbounded <ReadOnlyMemory <byte> >();
     _        = Task.Run(RunReceiveAsync);
 }
Exemplo n.º 7
0
        /// <inheritdoc/>
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            // I assume the user correctly overrides the method and doesn't hide it.
            var method = GetType().GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic);

            if (method.DeclaringType == typeof(DiscordClientService))
            {
                return(Task.CompletedTask);
            }

            _cts         = Cts.Linked(cancellationToken);
            _executeTask = Task.Run(async() =>
            {
                try
                {
                    await ExecuteAsync(_cts.Token).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "An exception occurred while executing {0}.", GetType().Name);
                    throw;
                }
            }, cancellationToken);

            if (_executeTask.IsCompleted)
            {
                return(_executeTask);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 8
0
        public async Task StopAsync( )
        {
            if (!IsRunning)
            {
                return;
            }
            IsRunning = false;

            Logger.Info("Stopping Bot");

            FiatConverter.StopMonitor( );
            if (!Cts.IsCancellationRequested)
            {
                Cts.Cancel( );
            }

            var services = Services.ToList( );

            foreach (var service in services)
            {
                await DetachAsync(service).ConfigureAwait(false);
            }

            Terminate?.Invoke(this);
        }
 public void CloseForm()
 {
     Cts.Cancel();
     Thread.Sleep(1000);
     ClientStream.Close();
     ClientStream.Dispose();
 }
Exemplo n.º 10
0
        /// <inheritdoc/>
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            var method = GetType().GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(CancellationToken) }, null);

            if (method.DeclaringType == method.GetBaseDefinition().DeclaringType)
            {
                return(Task.CompletedTask);
            }

            _cts         = Cts.Linked(cancellationToken);
            _executeTask = Task.Run(async() =>
            {
                try
                {
                    await ExecuteAsync(_cts.Token).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "An exception occurred while executing {0}.", GetType().Name);
                    throw;
                }
            }, cancellationToken);

            if (_executeTask.IsCompleted)
            {
                return(_executeTask);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 11
0
        internal void CheckForLongTurns()
        {
            if ((CurrentWorkItem == null && CurrentTask == null) ||
                (Utils.Since(CurrentStateStarted) <= OrleansTaskScheduler.TurnWarningLengthThreshold))
            {
                return;
            }

            // Since this thread is running a long turn, which (we hope) is blocked on some IO
            // or other external process, we'll create a replacement thread and tell this thread to
            // exit when it's done with the turn.
            // Note that we only do this if the current load is reasonably low and the current thread
            // count is reasonably small.
            if (!pool.InjectMoreWorkerThreads || pool.BusyWorkerCount >= MAX_THREAD_COUNT_TO_REPLACE ||
                (Silo.CurrentSilo == null || !(Silo.CurrentSilo.Metrics.CpuUsage < MAX_CPU_USAGE_TO_REPLACE)))
            {
                return;
            }

            if (Cts.IsCancellationRequested)
            {
                return;
            }

            // only create a new thread once per slow thread!
            Log.Warn(ErrorCode.SchedulerTurnTooLong2, string.Format(
                         "Worker pool thread {0} (ManagedThreadId={1}) has been busy for long time: {2}; creating a new worker thread",
                         Name, ManagedThreadId, GetThreadStatus()));
            Cts.Cancel();
            pool.CreateNewThread();
            // Consider: mark the activation running a long turn to reduce it's time quantum
        }
            private void DisplayAll()
            {
                CancellationToken token = Cts.Token;

                try
                {
                    foreach (var input in Input.GetConsumingEnumerable())
                    {
                        if (token.IsCancellationRequested)
                        {
                            break;
                        }

                        Console.WriteLine(input.SeqId + ": " + input.Value + " & ");
                    }
                }
                catch (Exception ex)
                {
                    if (!(ex is OperationCanceledException))
                    {
                        Cts.Cancel();
                        throw;
                    }
                }
            }
Exemplo n.º 13
0
        /// <summary>
        ///     Instantiates a new <see cref="Repeater"/>.
        /// </summary>
        /// <param name="client"> The client to execute the requests with. </param>
        /// <param name="options"> The optional request options. </param>
        protected Repeater(IRestClient client, IRestRequestOptions options = null)
        {
            Client  = client;
            Options = options;

            _cts = new Cts();
            _    = Task.Run(RunAsync);
        }
Exemplo n.º 14
0
 public ValueTask StartAsync(TimeSpan interval)
 {
     Interval         = interval;
     _lastSend        = null;
     _lastAcknowledge = null;
     _cts             = new Cts();
     _task            = Task.Run(InternalRunAsync, _cts.Token);
     return(default);
 public virtual void Cancel()
 {
     if (IsCancelable() && !IsCanceled)
     {
         IsCanceled = true;
         Cts.Cancel();
     }
 }
Exemplo n.º 16
0
        /// <summary>
        ///     Instantiates a new <see cref="Repeater"/>.
        /// </summary>
        /// <param name="client"> The client to execute the requests with. </param>
        /// <param name="options"> The optional request options. </param>
        /// <param name="cancellationToken"> The cancellation token to observe. </param>
        protected Repeater(IRestClient client, IRestRequestOptions options = null, CancellationToken cancellationToken = default)
        {
            Client  = client;
            Options = options;

            _cts = Cts.Linked(cancellationToken);
            _    = Task.Run(RunAsync, cancellationToken);
        }
Exemplo n.º 17
0
 public void Unsubscribe(CacheNotifyAction action)
 {
     Cts.TryGetValue(GetChannelName(action), out var source);
     if (source != null)
     {
         source.Cancel();
     }
 }
Exemplo n.º 18
0
        public async ValueTask <Stream> ReceiveAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            await _receiveSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                _receiveStream.Position = 0;
                _receiveStream.SetLength(0);
                do
                {
                    // See _limboCts for more info on cancellation.
                    var receiveTask = _ws.ReceiveAsync(_receiveBuffer, _limboCts.Token).AsTask();
                    using (var infiniteCts = Cts.Linked(cancellationToken))
                    {
                        var infiniteTask = Task.Delay(Timeout.Infinite, infiniteCts.Token);
                        var task         = await Task.WhenAny(infiniteTask, receiveTask).ConfigureAwait(false);

                        infiniteCts.Cancel();
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException(cancellationToken);
                    }

                    var result = await receiveTask.ConfigureAwait(false);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        var closeStatus  = _ws.CloseStatus;
                        var closeMessage = _ws.CloseMessage;
                        try
                        {
                            await _ws.CloseOutputAsync(closeStatus.GetValueOrDefault(), closeMessage, default).ConfigureAwait(false);
                        }
                        catch { }

                        throw new WebSocketClosedException(closeStatus, closeMessage);
                    }

                    _receiveStream.Write(_receiveBuffer.AsSpan(0, result.Count));
                    if (!result.EndOfMessage)
                    {
                        continue;
                    }

                    if (result.MessageType != WebSocketMessageType.Binary)
                    {
                        _receiveStream.Position = 0;
                        return(_receiveStream);
                    }

                    _receiveStream.TryGetBuffer(out var streamBuffer);

                    // We check the data for the ZLib flush which marks the end of the actual message.
                    if (streamBuffer.Count < 4 || BinaryPrimitives.ReadUInt32BigEndian(streamBuffer[^ 4..]) != 0x0000FFFF)
Exemplo n.º 19
0
        static void Exit(ExitResult result)
        {
            if (Cts != null)
            {
                Cts.Dispose();
            }

            Environment.Exit((int)result);
        }
Exemplo n.º 20
0
 public void Clear()
 {
     Cts?.Dispose();
     Cts = new CancellationTokenSource();
     Package.FileName      = null;
     Package.TotalFileSize = 0;
     Package.BytesReceived = 0;
     Package.Chunks        = null;
 }
Exemplo n.º 21
0
 private void Label3_Click(object sender, EventArgs e)
 {
     Cts.Cancel();
     if (Listener != null)
     {
         Listener.Stop();
     }
     this.Close();
 }
Exemplo n.º 22
0
 public static void Exit(ExitResult result)
 {
     if (Cts != null && !Cts.Token.CanBeCanceled)
     {
         Cts.Cancel();
         Cts.Dispose();
     }
     Environment.Exit((int)result);
 }
Exemplo n.º 23
0
 /// <summary>
 /// Clean up any resources being used.
 /// </summary>
 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && (components != null))
     {
         components.Dispose();
         Cts.Dispose();
     }
     base.Dispose(disposing);
 }
Exemplo n.º 24
0
        public override void Begin(Func <CancellationToken, Task> action = null, Action <Exception> onError = null)
        {
            ThrowIfDisposed();

            lock (Sync)
            {
                if (IsActive)
                {
                    return;
                }

                IsActive = true;

                Cts?.Dispose();

                Cts = new CancellationTokenSource();
            }

            if (action != null)
            {
                Action = action;
            }

            if (onError != null)
            {
                ErrorAction = onError;
            }

            Task = Task.Run(async() =>
            {
                while (!Cts.IsCancellationRequested)
                {
                    try { await Action(Cts.Token).ConfigureAwait(false); }
                    catch (OperationCanceledException) { /* ignored */ }
                    catch (Exception e)
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            try { ErrorAction?.Invoke(e); }
                            catch { /* ignored */ }

                            OnError(e);
                        }
                    }

                    try
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            await DelayAsync(Cts.Token).ConfigureAwait(false);
                        }
                    }
                    catch { /* ignored */ }
                }
            });
        }
        private void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            Cts?.Dispose( );
            fiatMonitor?.Dispose( );
        }
Exemplo n.º 26
0
    public async Task ShouldCancel_WhenCancellationRequested(NotificatorConnection sut)
    {
        var result = sut.ReceiveAsync(Cts.Token);

        await Wait();

        Assert.False(result.IsCompleted);

        Cts.Cancel();
        await Assert.ThrowsAsync <OperationCanceledException>(() => result.AsTask());
    }
Exemplo n.º 27
0
        internal async Task DisableAsync()
        {
            Cts.Cancel();
            await Task;

            Task.Dispose();

            var stillDisabledEvent = new StillDisabledEvent(Id);

            Kafka.ProduceEventAsJson(nameof(StillDisabledEvent), stillDisabledEvent);
        }
Exemplo n.º 28
0
 public void Cancel()
 {
     lock (disposing)
     {
         if (IsDisposed)
         {
             return;
         }
         Cts.Cancel();
     }
 }
Exemplo n.º 29
0
        public async Task ShutdownZvs()
        {
            if (_zvsMutex != null)
            {
                _zvsMutex.ReleaseMutex();
            }

            await Log.ReportInfoAsync("Shutting down", Cts.Token);

            Cts.Cancel();
            Current.Shutdown();
        }
    public async Task WithTimeout_ShouldSucceedWhenCompleted()
    {
        var result = Task.Run(async() =>
        {
            await Task.Delay(1);
        }).WithTimeoutAsync(TimeSpan.FromSeconds(2));
        await result;

        Cts.Cancel();

        Assert.True(result.IsCompletedSuccessfully);
    }