System.Threading.CancellationTokenSource.CreateLinkedTokenSource(System.Threading.CancellationToken, System.Threading.CancellationToken)

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

107 Examples 7

1. Example

Project: Discord.Net
Source File: DefaultRestClient.cs
private async Task<RestResponse> SendInternalAsync(HttpRequestMessage request, CancellationToken cancelToken, bool headerOnly)
        {
            cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_cancelToken, cancelToken).Token;
            HttpResponseMessage response = await _client.SendAsync(request, cancelToken).ConfigureAwait(false);
            
            var headers = response.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
            var stream = !headerOnly ? await response.Content.ReadAsStreamAsync().ConfigureAwait(false) : null;

            return new RestResponse(response.StatusCode, headers, stream);
        }

2. Example

Project: Foundatio
Source File: QueueBase.cs
protected CancellationToken GetLinkedDisposableCanncellationToken(CancellationToken cancellationToken) {
            if (cancellationToken.IsCancellationRequested)
                return cancellationToken;

            return CancellationTokenSource.CreateLinkedTokenSource(_queueDisposedCancellationTokenSource.Token, cancellationToken).Token;
        }

3. Example

Project: google-cloud-dotnet
Source File: Transaction.cs
private CancellationToken GetEffectiveCancellationToken(CancellationToken other) =>
            !CancellationToken.CanBeCanceled ? other
            : !other.CanBeCanceled ? CancellationToken
            : CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, other).Token;

4. Example

Project: redfoxmq
Source File: InProcSocket.cs
public MessageFrame Read(CancellationToken cancellationToken)
        {
            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken))
            {
                return _readStream.Dequeue(cts.Token);
            }
        }

5. Example

Project: IFramework
Source File: CommandBus.cs
protected IFramework.Message.MessageState BuildMessageState(IMessageContext messageContext, CancellationToken cancellationToken)
        {
            var pendingRequestsCts = new CancellationTokenSource();
            CancellationTokenSource linkedCts = CancellationTokenSource
                   .CreateLinkedTokenSource(cancellationToken, pendingRequestsCts.Token);
            cancellationToken = linkedCts.Token;
            var source = new TaskCompletionSource<object>();
            var state = new IFramework.Message.MessageState
            {
                MessageID = messageContext.MessageID,
                TaskCompletionSource = source,
                CancellationToken = cancellationToken,
                MessageContext = messageContext
            };
            return state;
        }

6. Example

Project: IFramework
Source File: CommandBus.cs
protected IFramework.Message.MessageState BuildMessageState(IMessageContext messageContext, CancellationToken cancellationToken)
        {
            var pendingRequestsCts = new CancellationTokenSource();
            CancellationTokenSource linkedCts = CancellationTokenSource
                   .CreateLinkedTokenSource(cancellationToken, pendingRequestsCts.Token);
            cancellationToken = linkedCts.Token;
            var source = new TaskCompletionSource<object>();
            var state = new IFramework.Message.MessageState
            {
                MessageID = messageContext.MessageID,
                TaskCompletionSource = source,
                CancellationToken = cancellationToken,
                MessageContext = messageContext
            };
            return state;
        }

7. Example

Project: IFramework
Source File: CommandBus.cs
protected MessageState BuildMessageState(IMessageContext messageContext, CancellationToken cancellationToken)
        {
            var pendingRequestsCts = new CancellationTokenSource();
            CancellationTokenSource linkedCts = CancellationTokenSource
                   .CreateLinkedTokenSource(cancellationToken, pendingRequestsCts.Token);
            cancellationToken = linkedCts.Token;
            var source = new TaskCompletionSource<object>();
            var state = new MessageState
            {
                MessageID = messageContext.MessageID,
                TaskCompletionSource = source,
                CancellationToken = cancellationToken,
                MessageContext = messageContext
            };
            return state;
        }

8. Example

Project: octokit.net
Source File: HttpClientAdapter.cs
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        static CancellationToken GetCancellationTokenForRequest(IRequest request, CancellationToken cancellationToken)
        {
            var cancellationTokenForRequest = cancellationToken;

            if (request.Timeout != TimeSpan.Zero)
            {
                var timeoutCancellation = new CancellationTokenSource(request.Timeout);
                var unifiedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token);

                cancellationTokenForRequest = unifiedCancellationToken.Token;
            }
            return cancellationTokenForRequest;
        }

9. Example

Project: Discord.Net
Source File: UnstableUdpClient.cs
public void SetCancelToken(CancellationToken cancelToken)
        {
            _parentToken = cancelToken;
            _cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _cancelTokenSource.Token).Token;
        }

10. Example

Project: Discord.Net
Source File: UnstableWebSocketClient.cs
public void SetCancelToken(CancellationToken cancelToken)
        {
            _parentToken = cancelToken;
            _cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _cancelTokenSource.Token).Token;
        }

11. Example

Project: Discord.Net
Source File: WS4NetClient.cs
public void SetCancelToken(CancellationToken cancelToken)
        {
            _parentToken = cancelToken;
            _cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _cancelTokenSource.Token).Token;
        }

12. Example

Project: Discord.Net
Source File: CachedRestClient.cs
public void SetCancelToken(CancellationToken cancelToken)
        {
            _parentToken = cancelToken;
            _cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _cancelTokenSource.Token).Token;
        }

13. Example

Project: SmartStoreNET
Source File: AsyncRunner.cs
public CancellationTokenSource CreateCompositeCancellationTokenSource(CancellationToken userCancellationToken)
		{
			if (userCancellationToken == CancellationToken.None)
			{
				return _shutdownCancellationTokenSource;
			}
			return CancellationTokenSource.CreateLinkedTokenSource(_shutdownCancellationTokenSource.Token, userCancellationToken);
		}

14. Example

Project: plexus-interop
Source File: InvocationSendProcessor.cs
public Task<bool> WaitWriteAvailableAsync(CancellationToken cancellationToken = default)
        {
            using (var cancellation = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, cancellationToken))
            {
                return _buffer.WaitWriteAvailableAsync(cancellation.Token);
            }
        }

15. Example

Project: lime-csharp
Source File: WebSocketTransport.cs
public override async Task<Envelope> ReceiveAsync(CancellationToken cancellationToken)
        {
            if (WebSocket.State != WebSocketState.Open || _listenerTask == null)
            {
                throw new InvalidOperationException("The connection was not initialized. Call OpenAsync first.");
            }

            if (_listenerTask.IsCompleted)
            {
                // Awaits the listener task to throw any exception to the caller
                await _listenerTask.WithCancellation(cancellationToken).ConfigureAwait(false);
                throw new InvalidOperationException("The listener task is completed");
            }

            using (
                var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
                    _listenerCts.Token))
            {
                return await _receivedEnvelopeBufferBlock.ReceiveAsync(linkedCts.Token).ConfigureAwait(false);
            }
        }

16. Example

Project: lime-csharp
Source File: WebSocketTransportListener.cs
public async Task<ITransport> AcceptTransportAsync(CancellationToken cancellationToken)
        {
            if (_acceptTransportTask == null) throw new InvalidOperationException("The listener is not active");
            if (_acceptTransportTask.IsCompleted)
            {
                await _acceptTransportTask.WithCancellation(cancellationToken).ConfigureAwait(false);
                throw new InvalidOperationException("The listener task is completed");
            }

            using (
                var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
                    _acceptTransportCts.Token))
            {
                return await _transportBufferBufferBlock.ReceiveAsync(linkedCts.Token).ConfigureAwait(false);
            }
        }

17. Example

Project: WebAPIDoodle
Source File: HttpControllerHandler.cs
public override Task ProcessRequestAsync(HttpContext context) {

            CancellationTokenSource cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
                context.Request.TimedOutToken, 
                context.Response.ClientDisconnectedToken);

            CancellationToken cancellationToken = cancellationTokenSource.Token;

            throw new NotImplementedException();
        }

18. Example

Project: WCell
Source File: CancellationTokenExtensions.cs
public static CancellationTokenSource CreateLinkedSource(this CancellationToken token)
        {
            return CancellationTokenSource.CreateLinkedTokenSource(token, new CancellationToken());
        }

19. Example

Project: xamarin-bluetooth-le
Source File: DeviceBase.cs
public static CancellationTokenSource GetCombinedSource(this ICancellationMaster cancellationMaster, CancellationToken token)
        {
            return CancellationTokenSource.CreateLinkedTokenSource(cancellationMaster.TokenSource.Token, token);
        }

20. Example

Project: XamarinComponents
Source File: DownloadUtils.cs
public static Stream ObtainExclusiveFileLock (string file, CancellationToken cancelToken, TimeSpan timeout, ILogger log = null)
		{
			var linkedCancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource (
				cancelToken,
				 new CancellationTokenSource (timeout).Token);
			
			while (!linkedCancelTokenSource.IsCancellationRequested) {
				try {
					var lockStream = File.Open (file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
					return lockStream;
				} catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) {
					Thread.Sleep (100);
				} catch (Exception ex) {
					log?.LogErrorFromException (ex);
				}
			}

			return null;
		}

21. Example

Project: roslyn
Source File: ServiceHubServiceBase.cs
protected async Task<T> RunServiceAsync<T>(Func<CancellationToken, Task<T>> callAsync, CancellationToken cancellationToken)
        {
            AssetStorage.UpdateLastActivityTime();

            // merge given cancellation token with shutdown cancellation token. it looks like if cancellation and disconnection happens
            // almost same time, we might not get cancellation message back from stream json rpc and get disconnected
            // https://github.com/Microsoft/vs-streamjsonrpc/issues/64
            using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, ShutdownCancellationToken))
            {
                try
                {
                    return await callAsync(mergedCancellation.Token).ConfigureAwait(false);
                }
                catch (Exception ex) when (LogUnlessCanceled(ex, mergedCancellation.Token))
                {
                    // never reach
                    throw ExceptionUtilities.Unreachable;
                }
            }
        }

22. Example

Project: roslyn
Source File: ServiceHubServiceBase.cs
protected async Task RunServiceAsync(Func<CancellationToken, Task> callAsync, CancellationToken cancellationToken)
        {
            AssetStorage.UpdateLastActivityTime();

            // merge given cancellation token with shutdown cancellation token. it looks like if cancellation and disconnection happens
            // almost same time, we might not get cancellation message back from stream json rpc and get disconnected
            // https://github.com/Microsoft/vs-streamjsonrpc/issues/64
            using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, ShutdownCancellationToken))
            {
                try
                {
                    await callAsync(mergedCancellation.Token).ConfigureAwait(false);
                }
                catch (Exception ex) when (LogUnlessCanceled(ex, mergedCancellation.Token))
                {
                    // never reach
                    return;
                }
            }
        }

23. Example

Project: roslyn
Source File: ServiceHubServiceBase.cs
protected T RunService<T>(Func<CancellationToken, T> call, CancellationToken cancellationToken)
        {
            AssetStorage.UpdateLastActivityTime();

            // merge given cancellation token with shutdown cancellation token. it looks like if cancellation and disconnection happens
            // almost same time, we might not get cancellation message back from stream json rpc and get disconnected
            // https://github.com/Microsoft/vs-streamjsonrpc/issues/64
            using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, ShutdownCancellationToken))
            {
                try
                {
                    return call(mergedCancellation.Token);
                }
                catch (Exception ex) when (LogUnlessCanceled(ex, mergedCancellation.Token))
                {
                    // never reach
                    return default;
                }
            }
        }

24. Example

Project: roslyn
Source File: ServiceHubServiceBase.cs
protected void RunService(Action<CancellationToken> call, CancellationToken cancellationToken)
        {
            AssetStorage.UpdateLastActivityTime();

            // merge given cancellation token with shutdown cancellation token. it looks like if cancellation and disconnection happens
            // almost same time, we might not get cancellation message back from stream json rpc and get disconnected
            // https://github.com/Microsoft/vs-streamjsonrpc/issues/64
            using (var mergedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, ShutdownCancellationToken))
            {
                try
                {
                    call(mergedCancellation.Token);
                }
                catch (Exception ex) when (LogUnlessCanceled(ex, mergedCancellation.Token))
                {
                    // never reach
                }
            }
        }

25. Example

Project: Foundatio
Source File: QueueBase.cs
protected CancellationToken GetDequeueCanncellationToken(CancellationToken linkedDisposedCancellationToken) {
            if (linkedDisposedCancellationToken.IsCancellationRequested)
                return linkedDisposedCancellationToken;

            return CancellationTokenSource.CreateLinkedTokenSource(linkedDisposedCancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token).Token;
        }

26. Example

Project: WebQQWeChat
Source File: AbstractActionFuture.cs
public QQActionEvent WaitFinalEvent(CancellationToken token)
        {
            _cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, token);
            return WaitFinalEvent();
        }

27. Example

Project: WebQQWeChat
Source File: AbstractActionFuture.cs
public Task<QQActionEvent> WhenFinalEvent(CancellationToken token)
        {
            _cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, token);
            return WhenFinalEvent();
        }

28. Example

Project: peercaststation
Source File: ConnectionStream.cs
private CancellationTokenSource LinkTimeoutCancelTokenSource(int timeout, CancellationToken cancel_token)
    {
      if (timeout>0) {
        return CancellationTokenSource.CreateLinkedTokenSource(
          closedCancelSource.Token,
          (new CancellationTokenSource(timeout)).Token,
          cancel_token
        );
      }
      else {
        return CancellationTokenSource.CreateLinkedTokenSource(
          closedCancelSource.Token,
          cancel_token
        );
      }
    }

29. Example

Project: peercaststation
Source File: PCPPongOutputStream.cs
protected override async Task<StopReason> DoProcess(CancellationToken cancel_token)
    {
      var timeout_source = CancellationTokenSource.CreateLinkedTokenSource(
        new CancellationTokenSource(3000).Token,
        cancel_token);
      while (!timeout_source.IsCancellationRequested) {
        var atom = await Connection.ReadAtomAsync(timeout_source.Token);
        await ProcessAtom(atom, cancel_token);
      }
      return StopReason.OffAir;
    }

30. Example

Project: MySqlConnector
Source File: MySqlConnection.cs
private async Task<ServerSession> CreateSessionAsync(IOBehavior ioBehavior, CancellationToken /n ..... /n //View Source file for more details /n }

31. Example

Project: Discord.Net
Source File: UnstableRestClient.cs
private async Task<RestResponse> SendInternalAsync(HttpRequestMessage request, CancellationToken cancelToken, bool headerOnly)
        {
            if (!UnstableCheck())
                throw new TimeoutException();

            cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_cancelToken, cancelToken).Token;
            HttpResponseMessage response = await _client.SendAsync(request, cancelToken).ConfigureAwait(false);
            
            var headers = response.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
            var stream = !headerOnly ? await response.Content.ReadAsStreamAsync().ConfigureAwait(false) : null;

            return new RestResponse(response.StatusCode, headers, stream);
        }

32. Example

Project: lime-csharp
Source File: ChannelBase.cs
private async Task SendAsync<T>(T envelope, CancellationToken cancellationToken) where T : Envelope, new()
        {
            if (!Transport.IsConnected)
            {
                throw new InvalidOperationException("The transport is not connected");
            }

            using (var timeoutCancellationTokenSource = new CancellationTokenSource(_sendTimeout))
            using (var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
                cancellationToken, timeoutCancellationTokenSource.Token))
            {
                await Transport.SendAsync(envelope, linkedCancellationTokenSource.Token).ConfigureAwait(false);
            }
        }

33. Example

Project: WebAPIDoodle
Source File: TimeoutHandler.cs
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

            var cts = new CancellationTokenSource();
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
            var linkedToken = linkedTokenSource.Token;
            var timer = new Timer(s_timerCallback, cts, -1, -1);

            request.RegisterForDispose(timer);
            request.RegisterForDispose(cts);
            request.RegisterForDispose(linkedTokenSource);

            timer.Change(_milliseconds, -1);

            return base.SendAsync(request, linkedToken).ContinueWith(task => 
                request.CreateResponse(HttpStatusCode.RequestTimeout), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnCanceled);
        }

34. Example

Project: google-cloud-dotnet
Source File: SimpleSubscriberTest.cs
public async Task<bool> MoveNext(CancellationToken cancellationToken)
                {
                    if (_msgsEn.MoveNext())
                    {
                        // TODO: This is not correct. The real server cancels the entire call if this cancellationtoken is cancelled.
                        using (var cts = CancellationTokenSource.CreateLinkedTokenSource(_ct, cancellationToken))
                        {
                            var isCancelled = await _taskHelper.ConfigureAwaitHideCancellation(
                                () => _scheduler.Delay(_msgsEn.Current.Action.PreInterval, cts.Token));
                            if (isCancelled)
                            {
                                // This mimics behaviour of a real server
                                throw new RpcException(new Status(StatusCode.Cancelled, "Operation cancelled"));
                            }
                            if (_msgsEn.Current.Action.MoveNextEx != null)
                            {
                                throw _msgsEn.Current.Action.MoveNextEx;
                            }
                            return true;
                        }
                    }
                    return false;
                }

35. Example

Project: redfoxmq
Source File: Requester.cs
public async Task<IMessage> RequestAsync(IMessage message, CancellationToken cancellationToken)
        {
            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, cancellationToken))
            {
                return await RequestWithCancellationToken(message, cts.Token).ConfigureAwait(false);
            }
        }

36. Example

Project: squidex
Source File: CompletionTimer.cs
private async Task WaitAsync(int intervall)
        {
            try
            {
                wakeupToken = new CancellationTokenSource();

                using (var cts = CancellationTokenSource.CreateLinkedTokenSource(stopToken.Token, wakeupToken.Token))
                {
                    await Task.Delay(intervall, cts.Token).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
            }
        }

37. Example

Project: equeue
Source File: PullMessageService.cs
public IEnumerable<QueueMessage> PullMessages(int maxCount, int timeoutMilliseconds, CancellationToken cancellation)
        {
            var totalMessages = new List<QueueMessage>();
            var timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellation, new CancellationTokenSource(timeoutMilliseconds).Token);

            lock (_lockObj)
            {
                //???????????
                //1. timeout???????
                //2. ????????maxCount?
                //3. ??????????????????????????????
                while (!timeoutCancellationTokenSource.IsCancellationRequested
                    && totalMessages.Count < maxCount
                    && (_pulledMessageQueue.Count > 0 || totalMessages.Count == 0))
                {
                    try
                    {
                        totalMessages.Add(_pulledMessageQueue.Take(timeoutCancellationTokenSource.Token));
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                }
            }

            return totalMessages;
        }

38. Example

Project: opc-ua-client
Source File: UaTcpSecureChannel.cs
public virtual async Task<IServiceResponse> RequestAsync(IServiceRequest request)
        {
            this.ThrowIfClosedOrNotOpening();
            this.TimestampHeader(request);
            var operation = new ServiceOperation(request);
            using (var timeoutCts = new CancellationTokenSource((int)request.RequestHeader.TimeoutHint))
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, this.channelCts.Token))
            using (var registration = linkedCts.Token.Register(o => ((ServiceOperation)o).TrySetException(new ServiceResultException(StatusCodes.BadRequestTimeout)), operation, false))
            {
                if (this.pendingRequests.Post(operation))
                {
                    return await operation.Task.ConfigureAwait(false);
                }

                throw new ServiceResultException(StatusCodes.BadSecureChannelClosed);
            }
        }

39. Example

Project: couchbase-net-client
Source File: CouchbaseRequestExecuter.cs
public override async Task<IQueryResult<T>> SendWithRetryAsync<T>(IQueryRequest qu/n ..... /n //View Source file for more details /n }

40. Example

Project: Wordpress-Client
Source File: ProgressStreamContent.cs
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();
                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);

                var readCount = await ParentStream.ReadAsync(buffer, offset, count, linked.Token);

                ReadCallback(readCount);
                return readCount;
            }

41. Example

Project: Wordpress-Client
Source File: ProgressStreamContent.cs
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();

                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);
                var task = ParentStream.WriteAsync(buffer, offset, count, linked.Token);

                WriteCallback(count);
                return task;
            }

42. Example

Project: google-cloud-dotnet
Source File: SimplePublisher.cs
private void DelaySendCurrentBatch()
        {
            // Pre-condition: Must be locked
            if (_batchDelayThreshold is TimeSpan batchDelayThreshold)
            {
                // read cancellation token here, in case the current batch changes before the task below starts.
                var timerCancellation =
                    CancellationTokenSource.CreateLinkedTokenSource(_currentBatch.TimerCts.Token, _hardStopCts.Token);
                // Ignore result of this Task. If it's cancelled, it's because the batch has already been sent.
                _taskHelper.Run(async () =>
                {
                    await _taskHelper.ConfigureAwait(_scheduler.Delay(batchDelayThreshold, timerCancellation.Token));
                    // If batch has already moved to queue, timerToken will have been cancelled.
                    lock (_lock)
                    {
                        // Check for cancellation inside lock to avoid race-condition.
                        if (!timerCancellation.IsCancellationRequested)
                        {
                            // Force queuing of the current batch, whatever the size.
                            // There will always be at least one message in the batch.
                            QueueCurrentBatch();
                        }
                    }
                    timerCancellation.Dispose();
                });
            }
        }

43. Example

Project: myManga
Source File: ContentDownloadManager.cs
public async Task<List<MangaObject>> SearchAsync(String SearchTerm, CancellationToken ct, IProgress<int> progress = null)
        {
            using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, cts.Token))
            { return await Task.Factory.StartNew(() => SearchMangaObjectAsync(SearchTerm, linkedCts.Token, progress)).Unwrap(); }
        }

44. Example

Project: ServiceFabric.Mocks
Source File: Lock.cs
private async Task<bool> Wait(int milliseconds, CancellationToken cancellationToken)
        {
            if (milliseconds > 0)
            {
                lock (_lockOwners)
                {
                    if (TokenSource == null)
                    {
                        TokenSource = new CancellationTokenSource();
                    }
                }

                var token = TokenSource.Token;

                CancellationTokenSource linkedTokenSource = null;
                try
                {
                    if (cancellationToken != default(CancellationToken))
                    {
                        linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, token);
                        token = linkedTokenSource.Token;
                    }

                    await Task.Delay(milliseconds, token);
                }
                catch (OperationCanceledException)
                {
                    // If the caller's cancellation token is cancelled then throw
                    cancellationToken.ThrowIfCancellationRequested();

                    // Otherwise the lock's cancellation token is cancelled, so the lock is available.
                    return true;
                }
                finally
                {
                    linkedTokenSource?.Dispose();
                }
            }

            return false;
        }

45. Example

Project: ModernHttpClient
Source File: ProgressStreamContent.cs
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();
                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);

                var readCount = await ParentStream.ReadAsync(buffer, offset, count, linked.Token);

                ReadCallback(readCount);
                return readCount;
            }

46. Example

Project: ModernHttpClient
Source File: ProgressStreamContent.cs
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();

                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);
                var task = ParentStream.WriteAsync(buffer, offset, count, linked.Token);

                WriteCallback(count);
                return task;
            }

47. Example

Project: Discord.Net
Source File: UnstableUdpClient.cs
public async Task StartInternalAsync(CancellationToken cancelToken)
        {
            await StopInternalAsync().ConfigureAwait(false);

            _cancelTokenSource = new CancellationTokenSource();
            _cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _cancelTokenSource.Token).Token;

            _udp = new UdpClient(0);

            _task = RunAsync(_cancelToken);
        }

48. Example

Project: Discord.Net
Source File: RequestQueue.cs
public async Task SetCancelTokenAsync(CancellationToken cancelToken)
        {
            await _tokenLock.WaitAsync().ConfigureAwait(false);
            try
            {
                _parentToken = cancelToken;
                _requestCancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancelToken, _clearToken.Token).Token;
            }
            finally { _tokenLock.Release(); }
        }

49. Example

Project: service-fabric-reverse-proxy
Source File: ProxyHandler.cs
private async Task<HttpResponseMessage> RedirectRequest(HttpRequestMessage request, Cancellati/n ..... /n //View Source file for more details /n }

50. Example

Project: RestBus
Source File: RestBusSubscriber.cs
public void Restart()
        {
            hasStarted.Set(true);

            //CLose connections a/n ..... /n //View Source file for more details /n }