示例#1
0
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();

            if (!_started)
            {
                throw new InvalidOperationException("The listener has not yet been started or has already been stopped.");
            }

            // cancel our token source to signal any in progress
            // ProcessMessageAsync invocations to cancel
            _cancellationTokenSource.Cancel();

            if (_receiver != null && _receiver.IsValueCreated)
            {
                await Receiver.CloseAsync();

                _receiver = CreateMessageReceiver();
            }
            if (_clientEntity != null)
            {
                await _clientEntity.CloseAsync();

                _clientEntity = null;
            }
            _started = false;
        }
        public void Dispose()
        {
            if (!_disposed)
            {
                // Running callers might still be using the cancellation token.
                // Mark it canceled but don't dispose of the source while the callers are running.
                // Otherwise, callers would receive ObjectDisposedException when calling token.Register.
                // For now, rely on finalization to clean up _cancellationTokenSource's wait handle (if allocated).
                _cancellationTokenSource.Cancel();

                if (_receiver != null && _receiver.IsValueCreated)
                {
                    Receiver.CloseAsync().Wait();
                    _receiver = null;
                }

                if (_sessionClient != null && _sessionClient.IsValueCreated)
                {
                    _sessionClient.Value.CloseAsync().Wait();
                    _sessionClient = null;
                }

                if (_clientEntity != null)
                {
                    _clientEntity.CloseAsync().Wait();
                    _clientEntity = null;
                }

                _stopAsyncSemaphore.Dispose();
                _cancellationTokenSource.Dispose();

                _disposed = true;
            }
        }