System.Threading.CancellationTokenSource.Dispose(bool)

Here are the examples of the csharp api System.Threading.CancellationTokenSource.Dispose(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

134 Examples 7

19 Source : TokenCredentialCache.cs
with MIT License
from Azure

public void Dispose()
        {
            if (this.isDisposed)
            {
                return;
            }

            this.cancellationTokenSource.Cancel();
            this.cancellationTokenSource.Dispose();
            this.isDisposed = true;
        }

19 Source : BatchAsyncStreamer.cs
with MIT License
from Azure

public void Dispose()
        {
            this.cancellationTokenSource.Cancel();
            this.cancellationTokenSource.Dispose();

            this.currentTimer.CancelTimer();
            this.currentTimer = null;
            this.timerTask = null;

            if (this.congestionControlTimer != null)
            {
                this.congestionControlTimer.CancelTimer();
                this.congestionControlTimer = null;
                this.congestionControlTask = null;
            }
        }

19 Source : PartitionSupervisorCore.cs
with MIT License
from Azure

public override void Dispose()
        {
            this.processorCancellation?.Dispose();
            this.renewerCancellation.Dispose();
        }

19 Source : GlobalEndpointManager.cs
with MIT License
from Azure

public void Dispose()
        {
            this.connectionPolicy.PreferenceChanged -= this.OnPreferenceChanged;
            if (!this.cancellationTokenSource.IsCancellationRequested)
            {
                // This can cause task canceled exceptions if the user disposes of the object while awaiting an async call.
                this.cancellationTokenSource.Cancel();
                // The background timer task can hit a ObjectDisposedException but it's an async background task
                // that is never awaited on so it will not be thrown back to the caller.
                this.cancellationTokenSource.Dispose();
            }
        }

19 Source : AsyncCacheNonBlocking.cs
with MIT License
from Azure

private void Dispose(bool disposing)
        {
            if (this.isDisposed)
            {
                return;
            }

            if (disposing)
            {
                try
                {
                    this.cancellationTokenSource.Cancel();
                    this.cancellationTokenSource.Dispose();
                }
                catch (ObjectDisposedException exception)
                {
                    // Need to access the exception to avoid unobserved exception
                    DefaultTrace.TraceInformation($"AsyncCacheNonBlocking was already disposed: {0}", exception);
                }

                this.isDisposed = true;
            }
        }

19 Source : ClientTelemetry.cs
with MIT License
from Azure

public void Dispose()
        {
            this.cancellationTokenSource.Cancel();
            this.cancellationTokenSource.Dispose();

            this.telemetryTask = null;
        }

19 Source : PartitionSupervisorTests.cs
with MIT License
from Azure

public void Dispose()
        {
            this.sut.Dispose();
            this.shutdownToken.Dispose();
        }

19 Source : KafkaListener.cs
with MIT License
from Azure

private async Task SafeCloseConsumerAsync()
        {
            if (Interlocked.Exchange(ref isClosed, 1) == 1)
            {
                return;
            }

            try
            {
                // Stop subscriber thread
                this.cancellationTokenSource.Cancel();

                // Stop function executor                
                if (this.functionExecutor != null)
                {
                    await this.functionExecutor.CloseAsync(TimeSpan.FromMilliseconds(TimeToWaitForRunningProcessToEnd));
                }

                // Wait for subscriber thread to end                
                if (this.subscriberFinished != null)
                {
                    await this.subscriberFinished.WaitAsync(TimeToWaitForRunningProcessToEnd);
                }

                if (this.consumer.IsValueCreated)
                {
                    var localConsumer = this.consumer.Value;
                    localConsumer.Unsubscribe();
                    localConsumer.Dispose();
                }
                
                this.functionExecutor?.Dispose();
                this.subscriberFinished?.Dispose();
                this.cancellationTokenSource.Dispose();                
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Failed to close Kafka listener");
            }
        }

19 Source : Connection.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            // ensure that we are in a cancelled state.
            _cancellationTokenSource?.Cancel();
            if (!_isDisposed)
            {
                // make sure we can't dispose twice
                _isDisposed = true;
                if (disposing)
                {
                    foreach (var t in _tasks.Values)
                    {
                        t.SetCancelled();
                    }

                    _writer?.Dispose();
                    _writer = null;
                    _reader?.Dispose();
                    _reader = null;

                    _cancellationTokenSource?.Dispose();
                    _cancellationTokenSource = null;
                }
            }
        }

19 Source : ServiceHubContextE2EFacts.cs
with MIT License
from Azure

private static async Task RunTestCore(string clientEndpoint, IEnumerable<string> clientAccessTokens, Func<Task> coreTask, int expectedReceivedMessageCount, ConcurrentDictionary<int, int> receivedMessageDict)
        {
            IList<HubConnection> connections = null;
            CancellationTokenSource cancellationTokenSource = null;
            try
            {
                connections = await CreateAndStartClientConnections(clientEndpoint, clientAccessTokens);
                cancellationTokenSource = new CancellationTokenSource();
                HandleHubConnection(connections, cancellationTokenSource);
                ListenOnMessage(connections, receivedMessageDict);

                replacedert.False(cancellationTokenSource.Token.IsCancellationRequested);

                await coreTask();
                await Task.Delay(_timeout);

                replacedert.False(cancellationTokenSource.Token.IsCancellationRequested);

                var receivedMessageCount = (from pair in receivedMessageDict
                                            select pair.Value).Sum();
                replacedert.Equal(expectedReceivedMessageCount, receivedMessageCount);
            }
            finally
            {
                cancellationTokenSource?.Dispose();
                if (connections != null)
                {
                    await Task.WhenAll(from connection in connections
                                       select connection.StopAsync());
                }
            }
        }

19 Source : TwinIdentityTokenUpdater.cs
with MIT License
from Azure

public void Dispose() {
            StopAsync().Wait();

            _updateTimer.Dispose();

            // _cts might be null if StartAsync() was never called.
            if (!(_cts is null)) {
                _cts.Dispose();
            }
        }

19 Source : BaseConnectProbe.cs
with MIT License
from Azure

public virtual void Dispose() {
            _lock.Wait();
            try {
                _cts.Cancel();
                _probe?.Dispose();
                DisposeArgsNoLock();
            }
            finally {
                _cts.Dispose();
                _lock.Release();
                _lock.Dispose();
            }
        }

19 Source : Worker.cs
with MIT License
from Azure

public async Task StopAsync() {
            await _lock.WaitAsync();
            try {
                if (_cts == null) {
                    return;
                }

                _logger.Information("Stopping worker...");
                _heartbeatTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

                // Inform services, that this worker has stopped working, so orchestrator can rereplacedign job
                if (_jobProcess != null) {
                    _jobProcess.Status = WorkerStatus.Stopped;
                    await SendHeartbeatWithoutResetTimer(); // need to be send before cancel the CancellationToken
                }

                // Stop worker
                _cts.Cancel();
                await _worker;
                _worker = null;

                System.Diagnostics.Debug.replacedert(_jobProcess == null);
                _logger.Information("Worker stopped.");
            }
            catch (OperationCanceledException) { }
            catch (Exception e) {
                _logger.Error(e, "Stopping worker failed.");
            }
            finally {
                _cts?.Dispose();
                _cts = null;
                _lock.Release();
            }
        }

19 Source : Worker.cs
with MIT License
from Azure

public void Dispose() {
            Try.Async(StopAsync).Wait();

            System.Diagnostics.Debug.replacedert(_jobProcess == null);
            _jobProcess?.Dispose();

            _cts?.Dispose();
            _heartbeatTimer.Dispose();
            _lock.Dispose();
        }

19 Source : Worker.cs
with MIT License
from Azure

public void Dispose() {
                _heartbeatTimer.Dispose();
                _jobScope.Dispose();
                _cancellationTokenSource.Dispose();
            }

19 Source : HttpTunnelHandlerFactory.cs
with MIT License
from Azure

public void Dispose() {
                _timeout.Dispose();
            }

19 Source : IoTHubFileNotificationHost.cs
with MIT License
from Azure

public void Dispose() {
            StopAsync().Wait();
            _client.Dispose();
            _cts.Dispose();
        }

19 Source : PortScanner.cs
with MIT License
from Azure

public void Dispose() {
            // Kill producer
            _cts.Cancel();
            // Clean up all probes
            _active = 0;
            foreach (var probe in _probePool) {
                probe.Dispose();
            }
            _probePool.Clear();
            _completion.TrySetCanceled();
            _cts.Dispose();
        }

19 Source : DiscoveryRequest.cs
with MIT License
from Azure

public void Dispose() {
            _cts.Dispose();
        }

19 Source : DiscoveryServices.cs
with MIT License
from Azure

public void Dispose() {
            Try.Async(StopDiscoveryRequestProcessingAsync).Wait();

            // Dispose
            _cts.Dispose();
            _timer.Dispose();
            _lock.Dispose();
        }

19 Source : SupervisorServices.cs
with MIT License
from Azure

public void Dispose() {
                StopAsync().Wait();
                _cts.Dispose();
            }

19 Source : ClientServices.cs
with MIT License
from Azure

public void Dispose() {
            Try.Op(() => _cts.Cancel());
            Try.Op(() => _timer.Dispose());
            foreach (var client in _clients.Values) {
                Try.Op(client.Dispose);
            }
            _clients.Clear();
            Try.Op(() => _cts.Dispose());
            _lock.Dispose();
            _appConfig = null;
        }

19 Source : ClientSession.cs
with MIT License
from Azure

public void Dispose() {
            CloseAsync().Wait();
            _cts.Dispose();
            _config.CertificateValidator.CertificateValidation -= OnValidate;
            _logger.Information("Session closed.");
        }

19 Source : ClientSession.cs
with MIT License
from Azure

public override void Dispose() {
                _tcs.TrySetCanceled();
                _cts.Dispose();
            }

19 Source : DefaultSessionManager.cs
with MIT License
from Azure

public void Dispose() {
            Try.Async(StopAsync).Wait();

            // Dispose
            _cts.Dispose();
            _lock.Dispose();
        }

19 Source : WebSocketMessageSocket.cs
with MIT License
from Azure

public void Dispose() {
            Close();
            _open.Dispose();
        }

19 Source : SessionServices.cs
with MIT License
from Azure

public void Dispose() {
                _cts.Cancel();
                _timeoutTimer?.Dispose();
                _cts.Dispose();
                _serverCertificate.Dispose();
            }

19 Source : ServerFactory.cs
with MIT License
from Azure

protected override void Dispose(bool disposing) {
                base.Dispose(disposing);
                _cts?.Dispose();
            }

19 Source : Program.cs
with MIT License
from Azure

public void Dispose() {
                _cts.Cancel();
                _server.Wait();
                _cts.Dispose();
            }

19 Source : Startup.cs
with MIT License
from Azure

public void Dispose() {
                Try.Async(StopAsync).Wait();
                _cts?.Dispose();
            }

19 Source : AsyncEndpointExecutor.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.batchTimer.Dispose();
                this.cts.Dispose();
                this.machine.Dispose();
            }
        }

19 Source : SyncEndpointExecutor.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.cts.Dispose();
                this.machine.Dispose();
                this.sync.Dispose();
            }
        }

19 Source : Router.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.cts.Dispose();
                this.dispatcher.Dispose();
                this.sync.Dispose();
            }
        }

19 Source : CertificateRenewal.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    this.timer.Dispose();
                    this.cts.Dispose();
                }
                catch (OperationCanceledException)
                {
                    // ignore by design
                }
            }
        }

19 Source : StoringAsyncEndpointExecutor.cs
with MIT License
from Azure

void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.cts.Dispose();
                ImmutableDictionary<uint, EndpointExecutorFsm> snapshot = this.prioritiesToFsms;
                this.prioritiesToFsms.CompareAndSet(snapshot, ImmutableDictionary<uint, EndpointExecutorFsm>.Empty);
                foreach (KeyValuePair<uint, EndpointExecutorFsm> entry in snapshot)
                {
                    var fsm = entry.Value;
                    fsm.Dispose();
                }
            }
        }

19 Source : ServerWebSocketChannel.cs
with MIT License
from Azure

void Abort()
        {
            try
            {
                Events.TransportAborted(this.correlationId);
                this.webSocket.Abort();
                this.webSocket.Dispose();
                this.writeCancellationTokenSource.Dispose();
            }
            catch (Exception ex) when (!ex.IsFatal())
            {
                Events.TransportAbortFailedException(this.correlationId, ex);
            }
            finally
            {
                this.webSocketClosed.TrySetResult(0);
            }
        }

19 Source : FilteringRoutingService.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.cts.Dispose();
                this.sync.Dispose();
                this.underlying.Dispose();
                foreach (INotifier notifier in this.Notifiers.Values)
                {
                    notifier.Dispose();
                }
            }
        }

19 Source : ServerWebSocketChannel.cs
with MIT License
from Azure

public void Dispose()
        {
            this.writeCancellationTokenSource.Dispose();
        }

19 Source : FrontendRoutingService.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.cts.Dispose();
                this.sync.Dispose();

                foreach (INotifier notifier in this.Notifiers.Values)
                {
                    notifier.Dispose();
                }
            }
        }

19 Source : Dispatcher.cs
with MIT License
from Azure

protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                ImmutableDictionary<string, IEndpointExecutor> snapshot = this.executors;
                foreach (IEndpointExecutor executor in snapshot.Values)
                {
                    executor.Dispose();
                }

                this.masterCheckpointer.Dispose();
                this.cts.Dispose();
                this.sync.Dispose();
            }
        }

19 Source : PeriodicTask.cs
with MIT License
from Azure

public void Dispose()
        {
            this.checkTimer?.Dispose();
            this.cts?.Cancel();
            this.cts?.Dispose();
        }

19 Source : BaseFixture.cs
with MIT License
from Azure

[TearDown]
        protected async Task AfterEachTestAsync()
        {
            this.profiler.Stop("Completed test '{Name}'", TestContext.CurrentContext.Test.Name);
            await Profiler.Run(
                async () =>
                {
                    this.cts.Dispose();
                    if ((!Context.Current.ISA95Tag) && (TestContext.CurrentContext.Result.Outcome != ResultState.Ignored))
                    {
                        using var cts = new CancellationTokenSource(Context.Current.TeardownTimeout);
                        await NUnitLogs.CollectAsync(this.testStartTime, cts.Token);
                        if (Context.Current.GetSupportBundle)
                        {
                            try
                            {
                                var supportBundlePath = Context.Current.LogFile.Match((file) => Path.GetDirectoryName(file), () => AppDomain.CurrentDomain.BaseDirectory);
                                await Process.RunAsync(
                                    "iotedge",
                                    $"support-bundle -o {supportBundlePath}/supportbundle-{TestContext.CurrentContext.Test.Name} --since \"{this.testStartTime:yyyy-MM-ddTHH:mm:ssZ}\"",
                                    cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Log.Error($"Failed to Get Support Bundle  Log with Error:{ex}");
                            }
                        }
                    }
                },
                "Completed test teardown");

            await this.AfterTestTimerEnds();
        }

19 Source : SimulatedPacketForwarder.cs
with MIT License
from Azure

public async Task StopAsync()
        {
            this.cancellationTokenSource?.Cancel();

            // wait until the stop push data job is finished
            if (this.pushDataTask != null)
            {
                await this.pushDataTask;
                this.pushDataTask = null;
            }

            // wait until the stop pull data job is finished
            if (this.pullDataTask != null)
            {
                await this.pullDataTask;
                this.pullDataTask = null;
            }

            // listener will stop once we dispose the udp client
            this.udpClient?.Dispose();
            this.cancellationTokenSource?.Dispose();
        }

19 Source : CancellationTokenExtensions.cs
with MIT License
from Azure

public static DisposableCancellationTokenPair LinkWithTimeout(this CancellationToken cancellationToken, TimeSpan? timeout)
        {
            if (timeout is { } someTimeout && someTimeout != Timeout.InfiniteTimeSpan)
            {
                if (someTimeout.Ticks < 0)
                    throw new ArgumentOutOfRangeException(nameof(timeout), timeout, null);

#pragma warning disable CA2000 // Dispose objects before losing scope (false positive)
                var timeoutCts = new CancellationTokenSource(someTimeout);
#pragma warning restore CA2000 // Dispose objects before losing scope
                if (!cancellationToken.CanBeCanceled)
                    return new DisposableCancellationTokenPair(timeoutCts, timeoutCts.Token);

                try
                {
#pragma warning disable CA2000 // Dispose objects before losing scope (false positive)
                    var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken);
#pragma warning restore CA2000 // Dispose objects before losing scope
                    return new DisposableCancellationTokenPair(linkedCts, linkedCts.Token);
                }
                catch
                {
                    timeoutCts.Dispose();
                    throw;
                }
            }
            else
            {
                return new DisposableCancellationTokenPair(null, cancellationToken);
            }
        }

19 Source : LoRaDeviceRegistry.cs
with MIT License
from Azure

public void ResetDeviceCache()
        {
            var oldResetCacheToken = this.resetCacheToken;
            this.resetCacheToken = new CancellationTokenSource();
            this.resetCacheChangeToken = new CancellationChangeToken(this.resetCacheToken.Token);

            if (oldResetCacheToken != null && !oldResetCacheToken.IsCancellationRequested && oldResetCacheToken.Token.CanBeCanceled)
            {
                oldResetCacheToken.Cancel();
                oldResetCacheToken.Dispose();

                Logger.Log("Device cache cleared", LogLevel.Information);
            }
        }

19 Source : LoRaDeviceRegistry.cs
with MIT License
from Azure

public void Dispose() => this.resetCacheToken.Dispose();

19 Source : WebSocketTextChannelTests.cs
with MIT License
from Azure

public async ValueTask DisposeAsync()
            {
                this.cts.Cancel();
                // Throws either OperationCanceledException or TaskCanceledException.
                await replacedert.ThrowsAnyAsync<OperationCanceledException>(() => this.webSocketTextChannelListenTask);
                this.cts.Dispose();
            }

19 Source : DeviceReconnectionSample.cs
with MIT License
from Azure-Samples

public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            s_cancellationTokenSource = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                s_cancellationTokenSource.Cancel();
                _logger.LogInformation("Sample execution cancellation requested; will exit.");
            };

            _logger.LogInformation($"Sample execution started, press Control+C to quit the sample.");

            try
            {
                await InitializeAndSetupClientAsync(s_cancellationTokenSource.Token);
                await Task.WhenAll(SendMessagesAsync(s_cancellationTokenSource.Token), ReceiveMessagesAsync(s_cancellationTokenSource.Token));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unrecoverable exception caught, user action is required, so exiting: \n{ex}");
                s_cancellationTokenSource.Cancel();
            }

            _initSemapreplaced.Dispose();
            s_cancellationTokenSource.Dispose();
        }

19 Source : FaceFinderVM.cs
with MIT License
from Azure-Samples

private async Task FindFacesAsync()
        {
            if (ComputerVisionKey.Equals(string.Empty) || FaceKey.Equals(string.Empty))
            {
                IsSettingsExpanded = true;
                MessageBox.Show("Enter your subscription key(s) in the dialog",
                    "Missing subscription key(s)", 
                    MessageBoxButton.OKCancel, MessageBoxImage.Asterisk);
                return;
            }

            isFindFacesButtonEnabled = false;

            ImageInfos.Clear();

            isCancelButtonEnabled = true;
            cancellationTokenSource = new CancellationTokenSource();

            await ProcessImageFilesForFacesAsync(imageFiles, cancellationTokenSource.Token);

            cancellationTokenSource.Dispose();
            isCancelButtonEnabled = false;

            isFindFacesButtonEnabled = true;

            // TODO: without this statement, app suspends updating UI until explicit focus change (mouse or key event)
            await Task.Delay(1);
        }

19 Source : Program.cs
with MIT License
from Azure-Samples

private static async Task SimulateDeviceToSendD2cAndReceiveD2c()
        {
            var tokenSource = new CancellationTokenSource();

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                tokenSource.Cancel();
                Console.WriteLine("Exiting...");
            };
            Console.WriteLine("Press CTRL+C to exit");

            await Task.WhenAll(
                AzureIoTHub.SendDeviceToCloudMessageAsync(tokenSource.Token),
                AzureIoTHub.ReceiveMessagesFromDeviceAsync(tokenSource.Token));

            tokenSource.Dispose();
        }

See More Examples