当前位置: 首页>>代码示例>>C#>>正文


C# CancellationToken.CreateLinked方法代码示例

本文整理汇总了C#中System.Threading.CancellationToken.CreateLinked方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationToken.CreateLinked方法的具体用法?C# CancellationToken.CreateLinked怎么用?C# CancellationToken.CreateLinked使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.CancellationToken的用法示例。


在下文中一共展示了CancellationToken.CreateLinked方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RunAsync


//.........这里部分代码省略.........
                                    runMode = runMode.Set(RunMode.Start, true).Clear(RunMode.Interactive, true);
                                    done = true;
                                    Console.WriteLine(ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive);
                                    Console.WriteLine(
                                        ServiceResources.ConsoleConnection_RunAsync_RunningNonInteractive2);
                                    Console.WriteLine();
                                    break;

                                default:
                                    return;
                            }
                        }
                        catch (TaskCanceledException)
                        {
                            return;
                        }
                        catch (Exception e)
                        {
                            if (!token.IsCancellationRequested)
                                Log.Add(e);
                        }
                    } while (!done);
                }
                else if (!runMode.HasFlag(RunMode.Interactive))
                    // If we don't show prompt and we're not interactive we should always start the service.
                    runMode = runMode.Set(RunMode.Start, true);

                // Create connection
                Console.Title = ServiceResources.ConsoleConnection_RunAsync_RunningTitle + service.ServiceName;
                ConsoleConnection connection = new ConsoleConnection(defaultLogFormat, defaultLoggingLevels, token);
                Guid id = service.Connect(connection);

                // Combined cancellation tokens.
                ITokenSource tSource = token.CreateLinked(connection._cancellationTokenSource.Token);
                try
                {
                    CancellationToken t = tSource.Token;

                    if (t.IsCancellationRequested) return;

                    if (runMode.HasFlag(RunMode.Start))
                    {
                        // Start the service
                        await service.StartService(ConsoleTextWriter.Default, null, t).ConfigureAwait(false);
                        if (t.IsCancellationRequested)
                            return;
                    }

                    if (!runMode.HasFlag(RunMode.Interactive))
                    {
                        // Wait to be cancelled as nothing to do.
                        await t.WaitHandle;
                        return;
                    }

                    do
                    {
                        // Flush logs
                        await Log.Flush(t).ConfigureAwait(false);

                        if (t.IsCancellationRequested) break;

                        WritePrompt(service);
                        try
                        {
                            string commandLine = await Console.In.ReadLineAsync().ConfigureAwait(false);
开发者ID:webappsuk,项目名称:CoreLibraries,代码行数:67,代码来源:ConsoleConnection.cs

示例2: Send

        public IObservable<Response> Send(
            [NotNull] Request request,
            CancellationToken token = default(CancellationToken))
        {
            OverlappingPipeClientStream stream = _stream;
            if (_state != PipeState.Connected ||
                stream == null)
                // ReSharper disable once AssignNullToNotNullAttribute
                return Observable.Empty<Response>();

            // ReSharper disable once AssignNullToNotNullAttribute
            return Observable.Create<Response>(
                async (observer, t) =>
                {
                    Debug.Assert(observer != null);

                    using (ITokenSource tokenSource = token.CreateLinked(t))
                    {
                        token = tokenSource.Token;

                        ConnectedCommand cr = new ConnectedCommand(request, observer);
                        _commandRequests.TryAdd(request.ID, cr);
                        try
                        {
                            await stream.WriteAsync(request.Serialize(), token).ConfigureAwait(false);
                            await cr.CompletionTask.WithCancellation(token).ConfigureAwait(false);
                        }
                            // ReSharper disable once EmptyGeneralCatchClause
                        catch
                        {
                        }

                        // If the command is not explicitly cancelled and is still running, and we've been cancelled
                        // then ask the server to cancel.
                        if (!cr.IsCancelled &&
                            !cr.IsCompleted &&
                            token.IsCancellationRequested)
                            try
                            {
                                using (CancellationTokenSource cts = Constants.FireAndForgetTokenSource)
                                    await CancelCommand(request.ID, cts.Token).ConfigureAwait(false);
                            }
                            catch (TaskCanceledException)
                            {
                            }

                        // Remove the command request.
                        _commandRequests.TryRemove(request.ID, out cr);
                    }
                });
        }
开发者ID:webappsuk,项目名称:CoreLibraries,代码行数:51,代码来源:NamedPipeClient.cs

示例3: TimerTask

        /// <summary>
        /// The timer task executes the callback asynchronously after set delays.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        // ReSharper disable once FunctionComplexityOverflow
        private async Task TimerTask(CancellationToken cancellationToken)
        {
            long startTicks = long.MinValue;
            long endTicks = long.MinValue;
            while (!cancellationToken.IsCancellationRequested)
                try
                {
                    CancellationTokenSource timeoutsChanged;

                    // Check we're not set to run immediately
                    if (Interlocked.Exchange(ref _runImmediate, 0) == 0)
                        do
                        {
                            // Create new cancellation token source and set _timeOutsChanged to it in a thread-safe none-locking way.
                            timeoutsChanged = new CancellationTokenSource();
                            CancellationTokenSource toc = Interlocked.Exchange(ref _timeOutsChanged, timeoutsChanged);
                            if (ReferenceEquals(toc, null))
                            {
                                toc = Interlocked.CompareExchange(ref _timeOutsChanged, null, timeoutsChanged);
                                if (!ReferenceEquals(toc, null))
                                    toc.Dispose();
                                return;
                            }

                            // If we have run immediate set at this point, we can't rely on the correct _timeOutsChanged cts being cancelled.
                            if (Interlocked.Exchange(ref _runImmediate, 0) > 0) break;

                            using (ITokenSource tokenSource = cancellationToken.CreateLinked(timeoutsChanged.Token))
                            {
                                // Check for pausing.
                                try
                                {
                                    await _pauseToken.WaitWhilePausedAsync(tokenSource.Token).ConfigureAwait(false);
                                }
                                catch (OperationCanceledException)
                                {
                                }
                                catch (Exception exception)
                                {
                                    if (!ReferenceEquals(_errorHandler, null))
                                        _errorHandler(exception);
                                }

                                if (cancellationToken.IsCancellationRequested) return;

                                // Get timeouts
                                TimeOuts timeOuts = _timeOuts;
                                if (ReferenceEquals(timeOuts, null)) return;

                                if (timeOuts.DueTimeMs < 0 ||
                                    (startTicks > timeOuts.DueTimeStamp && (timeOuts.MinimumGapMs < 0 || timeOuts.PeriodMs < 0)))
                                {
                                    // If we have infinite waits then we are effectively awaiting cancellation
                                    // ReSharper disable once PossibleNullReferenceException
                                    await tokenSource.ConfigureAwait(false);

                                    if (cancellationToken.IsCancellationRequested) return;
                                    continue;
                                }

                                // If all timeouts are zero we effectively run again immediately (after checking we didn't get a cancellation
                                // indicating the value have changed again).
                                if (timeOuts.DueTimeMs == 0 &&
                                    timeOuts.MinimumGapMs == 0 &&
                                    timeOuts.PeriodMs == 0)
                                    continue;

                                int wait;

                                if (startTicks > long.MinValue)
                                {
                                    // Calculate the wait time based on the minimum gap and the period.
                                    long now = HighPrecisionClock.Instance.NowTicks;
                                    int a = timeOuts.PeriodMs -
                                            (int)((now - startTicks) / NodaConstants.TicksPerMillisecond);
                                    int b = timeOuts.MinimumGapMs -
                                            (int)((now - endTicks) / NodaConstants.TicksPerMillisecond);
                                    int c = (int)((timeOuts.DueTimeStamp - now) / NodaConstants.TicksPerMillisecond);

                                    wait = Math.Max(a, Math.Max(b, c));
                                }
                                else
                                    // Wait the initial due time
                                    wait =
                                        (int)
                                            ((timeOuts.DueTimeStamp - HighPrecisionClock.Instance.NowTicks) /
                                             NodaConstants.TicksPerMillisecond);

                                // If we don't need to wait run again immediately (after checking values haven't changed).
                                if (wait < 1) continue;

                                try
                                {
                                    // Wait for set milliseconds
//.........这里部分代码省略.........
开发者ID:webappsuk,项目名称:CoreLibraries,代码行数:101,代码来源:AsyncTimer.cs

示例4: NamedPipeClient

        /// <summary>
        /// Initializes a new instance of the <see cref="NamedPipeClient" /> class.
        /// </summary>
        /// <param name="description">The client description.</param>
        /// <param name="server">The server.</param>
        /// <param name="onReceive">The action to call on receipt of a message.</param>
        /// <param name="token">The token.</param>
        private NamedPipeClient(
            [NotNull] string description,
            [NotNull] NamedPipeServerInfo server,
            [NotNull] Action<Message> onReceive,
            CancellationToken token = default(CancellationToken))
        {
            if (description == null) throw new ArgumentNullException("description");
            if (server == null) throw new ArgumentNullException("server");
            if (onReceive == null) throw new ArgumentNullException("onReceive");

            _server = server;

            _cancellationTokenSource = new CancellationTokenSource();
            CancellationToken disposeToken = _cancellationTokenSource.Token;

            _clientTask = Task.Run(
                async () =>
                {
                    try
                    {
                        using (ITokenSource tokenSource = token.CreateLinked(disposeToken))
                        using (
                            OverlappingPipeClientStream stream = new OverlappingPipeClientStream(
                                _server.Host,
                                _server.FullName,
                                PipeTransmissionMode.Message))
                        {
                            _state = PipeState.Open;

                            token = tokenSource.Token;

                            // We need to support cancelling the connect.
                            await stream.Connect(token).ConfigureAwait(false);

                            ConnectResponse connectResponse = null;
                            DisconnectResponse disconnectResponse = null;

                            if (!token.IsCancellationRequested)
                            {
                                // Set the stream.
                                _stream = stream;
                                _state = PipeState.AwaitingConnect;

                                // Kick off a connect request, but don't wait for it's result as we're the task that will receive it!
                                ConnectRequest connectRequest = new ConnectRequest(description);
                                await stream.WriteAsync(connectRequest.Serialize(), token).ConfigureAwait(false);

                                // Keep going as long as we're connected.
                                try
                                {
                                    while (stream.IsConnected &&
                                           !disposeToken.IsCancellationRequested)
                                    {
                                        // Read data in.
                                        byte[] data = await stream.ReadAsync(disposeToken).ConfigureAwait(false);

                                        if (data == null)
                                            break;

                                        // Deserialize the incoming message.
                                        Message message = Message.Deserialize(data);

                                        if (connectResponse == null)
                                        {
                                            // We require a connect response to start
                                            connectResponse = message as ConnectResponse;
                                            if (connectResponse == null ||
                                                connectResponse.ID != connectRequest.ID)
                                                break;

                                            _state = PipeState.Connected;
                                            _serviceName = connectResponse.ServiceName;

                                            Log.Add(
                                                LoggingLevel.Notification,
                                                () => ClientResources.Not_NamedPipeClient_Connection,
                                                connectResponse.ServiceName);

                                            TaskCompletionSource<NamedPipeClient> ccs =
                                                Interlocked.Exchange(ref _connectionCompletionSource, null);
                                            if (ccs != null)
                                                ccs.TrySetResult(this);

                                            // Observer the message.
                                            onReceive(message);
                                            continue;
                                        }

                                        // Check for disconnect, we don't observe the message until the disconnect is complete.
                                        disconnectResponse = message as DisconnectResponse;
                                        if (disconnectResponse != null)
                                            break;

//.........这里部分代码省略.........
开发者ID:webappsuk,项目名称:CoreLibraries,代码行数:101,代码来源:NamedPipeClient.cs


注:本文中的System.Threading.CancellationToken.CreateLinked方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。