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


C# CancellationToken.Register方法代码示例

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


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

示例1: SearchAsync

        public Task SearchAsync(string searchPattern, FileSearchMode mode, int count, IFileCollection files, CancellationToken cancellationToken)
        {
            if (String.IsNullOrEmpty(searchPattern))
            {
                files.Clear();
                foreach (string filePath in pinStateService.GetList())
                    files.Add(Path.GetFileNameWithoutExtension(filePath), filePath, true);

                if (lastCancellation != null)
                {
                    lastCancellation.Cancel();
                    lastCancellation = null;
                }

                return Task.FromResult(true);
            }

            if (cancellationToken.IsCancellationRequested)
                return Async.CompletedTask;

            lastCancellation = new CancellationTokenSource();
            cancellationToken.Register(() => lastCancellation.Cancel());

            Task result = innerService.SearchAsync(searchPattern, mode, count, files, lastCancellation.Token);
            return result;
        }
开发者ID:neptuo,项目名称:Productivity.SolutionRunner,代码行数:26,代码来源:PinnedForEmptyPatternFileSearchService.cs

示例2: CancellationTokenRegister_Exceptions

        public static void CancellationTokenRegister_Exceptions()
        {
            CancellationToken token = new CancellationToken();
            Assert.Throws<ArgumentNullException>(() => token.Register(null));

            Assert.Throws<ArgumentNullException>(() => token.Register(null, false));

            Assert.Throws<ArgumentNullException>(() => token.Register(null, null));
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:9,代码来源:CancellationTokenTests.cs

示例3: Run

        public void Run(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
                return;

            cancellationToken.Register(() => Receiver.CancelMessageWait());

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                    break;

                string currentMessage = null;
                try
                {
                    currentMessage = Receiver.GetNextMessage();
                    if (cancellationToken.IsCancellationRequested)
                        break;
                    ProcessMessage(currentMessage, cancellationToken);
                    Receiver.AckLastMessage();
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat(CultureInfo.InvariantCulture,
                        "Worker {0} encountered an error while attempting to process the message \"{1}\".",
                        InstanceId, currentMessage
                        );
                    Log.Error(ex);
                    Receiver.NackLastMessage();
                }
            }     
        }
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:32,代码来源:QueueMonitorWorker.cs

示例4: RunAsync

        public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
        {
            if (processStartInfo == null)
            {
                throw new ArgumentNullException("processStartInfo");
            }

            // force some settings in the start info so we can capture the output
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.CreateNoWindow = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var standardOutput = new List<string>();
            var standardError = new List<string>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true,
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
            };

            process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));

            cancellationToken.Register(() =>
            {
                tcs.TrySetCanceled();
                process.CloseMainWindow();
            });

            cancellationToken.ThrowIfCancellationRequested();

            if (process.Start() == false)
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start process"));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
开发者ID:mikecole,项目名称:ChocolateyGUI,代码行数:60,代码来源:ProcessEx.cs

示例5: ReadMultipartAsync

        public static async Task<IMultipartCollection> ReadMultipartAsync(this HttpRequest request, CancellationToken cancellationToken) {
            cancellationToken.ThrowIfCancellationRequested();

            request.EnableRewind();

            var parts = new MultipartCollection();

            using(cancellationToken.Register(request.HttpContext.Abort)) {
                var contentType = GetContentType(request);
                var boundary = GetBoundary(contentType);

                var multipartReader = new MultipartReader(boundary, request.Body);
                var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                while(section != null) {
                    var headers = new HeaderDictionary(section.Headers);
                    var contentDisposition = headers.GetContentDisposition();

                    await section.Body.DrainAsync(cancellationToken);

                    var part = new Multipart(request.Body, section.BaseStreamOffset.Value, section.Body.Length) {
                        Headers = headers
                    };
                    parts.Add(part);

                    section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                }

            }

            request.Body.Seek(0, SeekOrigin.Begin);

            return parts;
        }
开发者ID:migrap,项目名称:Migrap.AspNet.Http,代码行数:33,代码来源:HttpRequestExtensions.cs

示例6: UploadFromStreamAsync

 public static Task UploadFromStreamAsync(
     this CloudBlockBlob blob, Stream stream, CancellationToken ct = default(CancellationToken))
 {
     ICancellableAsyncResult ar = blob.BeginUploadFromStream(stream, null, null);
     ct.Register(ar.Cancel);
     return Task.Factory.FromAsync(ar, blob.EndUploadFromStream);
 }
开发者ID:glueckkanja,项目名称:sqlazurebak,代码行数:7,代码来源:StorageExtensions.cs

示例7: RSessionEvaluation

 public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) {
     Contexts = contexts;
     _evaluator = evaluator;
     _tcs = new TaskCompletionSource<object>();
     _ct = ct;
     ct.Register(() => _tcs.TrySetCanceled());
 }
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:7,代码来源:RSessionEvaluation.cs

示例8: Run

        public static void Run(this IWebHost host, Action<IServiceProvider> action, CancellationToken token, string shutdownMessage)
        {
            using (host)
            {
                host.Start();

                var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
                var applicationLifetime = host.Services.GetService<IApplicationLifetime>();

                Console.WriteLine($"Hosting environment: {hostingEnvironment.EnvironmentName}");
                Console.WriteLine($"Content root path: {hostingEnvironment.ContentRootPath}");

                var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
                if (serverAddresses != null)
                {
                    foreach (var address in serverAddresses)
                    {
                        Console.WriteLine($"Now listening on: {address}");
                    }
                }

                if (!string.IsNullOrEmpty(shutdownMessage))
                {
                    Console.WriteLine(shutdownMessage);
                }

                token.Register(state =>
                {
                    ((IApplicationLifetime)state).StopApplication();
                },
                applicationLifetime);

                action(host.Services);
            }
        }
开发者ID:yanghl22,项目名称:Orchard2,代码行数:35,代码来源:WebHostExtensions.cs

示例9: Run

 public async Task Run(CancellationToken token)
 {
     var tcs = new TaskCompletionSource<bool>();
     token.Register(() => { this.receiver.Close(); tcs.SetResult(true); });
     this.receiver.OnMessageAsync(rq => this.Respond(rq, this.responseFunction), new OnMessageOptions { AutoComplete = false });
     await tcs.Task;
 }
开发者ID:Azure-Samples,项目名称:azure-servicebus-messaging-samples,代码行数:7,代码来源:RequestReplyResponder.cs

示例10: ConnectAsync

        public async Task ConnectAsync(string webSocketServerUrl, CancellationToken token)
        {
            var uri = default(Uri);
            if (!Uri.TryCreate(webSocketServerUrl, UriKind.Absolute, out uri))
            {
                throw new ArgumentOutOfRangeException(nameof(webSocketServerUrl), "Expected valid URI argument.");
            }

            var retryCount = ConnectRetryCount;
            while (true)
            {
                var timeoutSource = new CancellationTokenSource(ConnectTimeoutMilliseconds);
                using (token.Register(timeoutSource.Cancel))
                {
                    try
                    {
                        await ConnectCoreAsync(uri, timeoutSource.Token).ConfigureAwait(false);
                        return;
                    }
                    catch (OperationCanceledException ex)
                    when (ex.CancellationToken == timeoutSource.Token)
                    {
                        token.ThrowIfCancellationRequested();
                    }
                    catch
                    {
                        if (--retryCount <= 0)
                        {
                            throw;
                        }
                    }
                }
            }
        }
开发者ID:chukcha-wtf,项目名称:react-native-windows,代码行数:34,代码来源:WebSocketJavaScriptExecutor.cs

示例11: Run

        private async Task Run(string directory, CancellationToken token)
        {
            var applicationBase = Environment.CurrentDirectory;
            var abPrefix = applicationBase.Length + 1;
            var relBoot = Path.GetDirectoryName(Path.GetFullPath(typeof(Boot).Assembly.Location).Substring(abPrefix));
            var relDir = Path.GetFullPath(directory).Substring(abPrefix);

            if (!token.IsCancellationRequested)
            {
                // ReSharper disable AccessToDisposedClosure
                var isolated = new Isolate<IsolatedRunner, IIsolatedRunner>(null, new AppDomainSetup { ApplicationBase = applicationBase, PrivateBinPath = relDir + Path.PathSeparator + relBoot });
                using(isolated)
                {
                    var reg = token.Register(() => isolated.Value.Cancel());using (reg)
                    try
                    {
                        Debug.WriteLine("Start " + directory);
                        await Task.Factory.StartNew(() => isolated.Value.Run(), token);
                    }
                    catch (TaskCanceledException)
                    {
                        
                    }
                    catch (Exception ex)
                    {
                        _log.Log(2, "Boot Run: " + ex.ToString());
                    }
                    Debug.WriteLine("Finish " + directory);
                }
                // ReSharper restore AccessToDisposedClosure
            }
        }
开发者ID:tanglebones,项目名称:ch-ioc,代码行数:32,代码来源:Boot.cs

示例12: GetWorkspaceAsync

        /// <summary>
        /// Get's the primary workspace asynchronously.
        /// </summary>
        public static Task<Workspace> GetWorkspaceAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            using (s_registryGate.DisposableWrite())
            {
                if (s_primaryWorkspace != null)
                {
                    return Task<Workspace>.FromResult(s_primaryWorkspace);
                }
                else
                {
                    var taskSource = new TaskCompletionSource<Workspace>();

                    if (cancellationToken.CanBeCanceled)
                    {
                        try
                        {
                            var registration = cancellationToken.Register(() =>
                            {
                                taskSource.TrySetCanceled();
                            });

                            taskSource.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                        }
                        catch
                        {
                        }
                    }

                    s_primaryWorkspaceTaskSourceList.Add(taskSource);
                    return taskSource.Task;
                }
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:36,代码来源:PrimaryWorkspace.cs

示例13: GetIntAsync

        public static Task<int> GetIntAsync(CancellationToken token = default(CancellationToken))
        {
            var tcs = new TaskCompletionSource<int>();

            if (token.IsCancellationRequested)
            {
                tcs.SetCanceled();
                return tcs.Task;
            }

            var timer = new System.Timers.Timer(3000);
            timer.AutoReset = false;
            timer.Elapsed += (s, e) =>
            {
                tcs.TrySetResult(10);
                timer.Dispose();
            };

            if (token.CanBeCanceled)
            {
                token.Register(() => {
                    tcs.TrySetCanceled();
                    timer.Dispose();
                });
            }

            timer.Start();
            return tcs.Task;
        }
开发者ID:hctan,项目名称:AsyncTest,代码行数:29,代码来源:AsyncFactory.cs

示例14: WaitForChangeAsync

        public async Task<string> WaitForChangeAsync(CancellationToken cancellationToken)
        {
            _watchedFiles = GetProjectFilesClosure(_rootProject);

            foreach (var file in _watchedFiles)
            {
                _fileWatcher.WatchDirectory(Path.GetDirectoryName(file));
            }

            var tcs = new TaskCompletionSource<string>();
            cancellationToken.Register(() => tcs.TrySetResult(null));

            Action<string> callback = path =>
            {
                // If perf becomes a problem, this could be a good starting point
                // because it reparses the project on every change
                // Maybe it could time-buffer the changes in case there are a lot
                // of files changed at the same time
                if (IsFileInTheWatchedSet(path))
                {
                    tcs.TrySetResult(path);
                }
            };

            _fileWatcher.OnFileChange += callback;
            var changedFile = await tcs.Task;
            _fileWatcher.OnFileChange -= callback;

            return changedFile;
        }
开发者ID:aspnet,项目名称:dotnet-watch,代码行数:30,代码来源:ProjectWatcher.cs

示例15: Start

        public Task Start(CancellationToken cancellationToken)
        {
            var completion = new TaskCompletionSource<bool>();
            cancellationToken.Register(() => ProcessExtensions.Terminate(_process));

            // Hook up the events. We don't hook up OutputDataReceived, because that wants to treat the data as strings; we need binary.
            _process.ErrorDataReceived += (sender, e) => OnErrorDataReceived(new ErrorDataReceivedEventArgs(e.Data));
            _process.Exited += (sender, e) =>
            {
                _process.WaitForExit(1000);
                _process.StandardOutput.Close();

                if (_process.ExitCode == 0)
                    completion.SetResult(true);
                else if (cancellationToken.IsCancellationRequested)
                    completion.SetCanceled();
                else
                    completion.SetException(new CodecProcessFailedException(_process.ExitCode));
            };

            _process.Start();
            _process.PriorityClass = ProcessPriorityClass.BelowNormal;
            _process.BeginErrorReadLine();

            return completion.Task;
        }
开发者ID:rlipscombe,项目名称:nemplode,代码行数:26,代码来源:CodecProcess.cs


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