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


C# Threading.CancellationTokenSource类代码示例

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


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

示例1: GenerateFirstCrossWord

 static ICrossBoard GenerateFirstCrossWord(ICrossBoard board, ICrossDictionary dictionary, string puzzle)
 {
     var placer = new PuzzlePlacer(board, puzzle);
     var cts = new CancellationTokenSource();
     var mre = new ManualResetEvent(false);
     ICrossBoard successFullBoard = null;
     foreach (var boardWithPuzzle in placer.GetAllPossiblePlacements(dictionary))
     {
         //boardWithPuzzle.WriteTo(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
         var gen = new CrossGenerator(dictionary, boardWithPuzzle);
         var t = Task.Factory.StartNew(() =>
                                   {
                                       foreach (var solution in gen.Generate())
                                       {
                                           successFullBoard = solution;
                                           cts.Cancel();
                                           mre.Set();
                                           break; //interested in the first one
                                       }
                                   }, cts.Token);
         if (cts.IsCancellationRequested)
             break;
     }
     mre.WaitOne();
     return successFullBoard;
 }
开发者ID:karasek,项目名称:CrossWord,代码行数:26,代码来源:Program.cs

示例2: testCancellation

        static void testCancellation()
        {
            IEnumerable<int> million = Enumerable.Range (3, 1000000);
            var cancelSource = new CancellationTokenSource();

            var primeNumberQuery =
                from n in million.AsParallel().WithCancellation (cancelSource.Token)
                where Enumerable.Range (2, (int) Math.Sqrt (n)).All (i => n % i > 0)
                select n;

            new Thread (() => {
                Thread.Sleep (100); // Cancel query after
                cancelSource.Cancel(); // 100 milliseconds.
            }).Start();

            try
            {
                // Start query running:
                int[] primes = primeNumberQuery.ToArray();
                // We'll never get here because the other thread will cancel us.
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Query canceled");
            }
        }
开发者ID:ethan-jiang-1,项目名称:msnet_sample,代码行数:26,代码来源:ClassChap23S1.cs

示例3: Run

        public void Run()
        {
            while (true)
            {
                var fetch = CommonTasks.ExecuteScript("Crawlers\\Scripts\\Bicing.js");
                var parse = fetch.ContinueWith<Tuple<Station, NameValueCollection>[]>(Parse, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                var store = parse.ContinueWith(Store, TaskContinuationOptions.OnlyOnRanToCompletion);

                try
                {
                    Task.WaitAll(fetch, parse, store);
                }
                catch (AggregateException e)
                {
                    e.Handle(x =>
                    {
                        System.Console.WriteLine(x.Message);
                        return true;
                    });
                }
                CancellationTokenSource source = new CancellationTokenSource();

                Task.Factory.StartNew(() => StationLoop(parse.Result), source.Token);

                Thread.Sleep(TimeSpan.FromHours(12));
                source.Cancel();
            }
        }
开发者ID:Costo,项目名称:BikeShare,代码行数:28,代码来源:BicingCrawler.cs

示例4: Dulicate_message_is_detected

        public void Dulicate_message_is_detected()
        {
            var builder = new CqrsEngineBuilder();
            builder.Memory(m =>
                {
                    m.AddMemorySender("in", s => s.IdGenerator(() => "same"));
                    m.AddMemoryRouter("in", c => "memory:null");
                });
            var observer = new ImmediateEventsObserver();
            builder.Advanced.RegisterObserver(observer);

            using (var token = new CancellationTokenSource())
            using (var build = builder.Build())
            {
                var sender = build.Resolve<IMessageSender>();
                sender.SendOne(new Message());
                sender.SendOne(new Message());

                observer.Event += @event =>
                    {
                        var e = @event as EnvelopeDuplicateDiscarded;

                        if (e != null)
                        {
                            token.Cancel();
                        }
                    };
                build.Start(token.Token);
                token.Token.WaitHandle.WaitOne(10000);
                Assert.IsTrue(token.IsCancellationRequested);
            }
        }
开发者ID:higheredgrowth,项目名称:lokad-cqrs,代码行数:32,代码来源:Given_duplicate_configuration.cs

示例5: GetDelegateTypes

        public static List<ClrType> GetDelegateTypes(ClrDump clrDump)
        {
            CancellationTokenSource token = new CancellationTokenSource();
            clrDump.MessageBus.BeginTask("Analyzing delegate types...", token);
            List<ClrType> delegates = new List<ClrType>();
            var delegateType = clrDump.GetClrType(typeof(MulticastDelegate).FullName);

            foreach(var type in  clrDump.AllTypes)
            {
                clrDump.MessageBus.Status($"Analyzing delegate type: {type.Name}");
                if (token.IsCancellationRequested)
                {
                    break;
                }

                if ( type.BaseType != null && type.BaseType == delegateType )
                {
                    clrDump.MessageBus.Status($"Analyzing delegate type: counting instances for {type.Name}");
                    int nb = clrDump.CountInstances(type);
                    if (nb > 0)
                    {
                        delegates.Add(type);
                    }
                }
            }

            clrDump.MessageBus.EndTask("Delegate types analyzed.");
            return delegates.GroupBy(t => t.Name).Select(g => g.First()).ToList();
        }
开发者ID:fremag,项目名称:MemoScope.Net,代码行数:29,代码来源:DelegatesAnalysis.cs

示例6: GeneratePasswords

        //probe==StartBounder
        public bool GeneratePasswords(int[] probe, int[] startBoundary, int[] endBoundary, int depth, int range, CancellationToken ct, CancellationTokenSource tokenSource, Action<string> sendPassword)
        {
            bool result = false;
            char[] probeChar = CharForThread(probe, _options);

            string probeString = String.Join("", probeChar);

            if (depth==0)
            {
                Console.WriteLine(probeString);
                if (VerifyMd5Hash(probeString))
                {
                    Password = probeString;
                    sendPassword(Password);
                    return true;
                }
                return false;
            }
            if (ct.IsCancellationRequested)
            {
                Console.WriteLine("Task is canceled");
            }

            if (probe.SequenceEqual(endBoundary)) return false;

            for (int i = 0; i < range; i++)
                {
                    probe[depth - 1] = i;
                    result = GeneratePasswords(probe, startBoundary, endBoundary, depth - 1, range, ct, tokenSource, sendPassword);
                    if (result) break;
                }
                return result;
        }
开发者ID:MariyaMindra,项目名称:MultithreadedReverseMD5HashCalculator,代码行数:34,代码来源:Generator.cs

示例7: Start

        public async Task Start(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                Settings.Default.Reload();
                var imageInfo = GetLatestImageInfo();
                if (imageInfo != null)
                {
                    var image = AssembleImageFrom(imageInfo);
                    var imageFile = SaveImage(image);
                    Wallpaper.Set(imageFile, Wallpaper.Style.Fit);
                }

                if (Settings.Default.Interval > 0)
                {
                    _internalTokenSource = new CancellationTokenSource();
                    using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, token))
                    {
                        try
                        {
                            await Task.Delay(TimeSpan.FromMinutes(Settings.Default.Interval), linkedCts.Token);
                        }
                        catch
                        {
                            // ignore exception raised by token cancellation
                        }
                    }
                }
            }
        }
开发者ID:lhmiranda,项目名称:live-earth-wallpaper,代码行数:30,代码来源:HimawariService.cs

示例8: Main

        private static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress +=
                (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

            // Since Console apps do not have a SyncronizationContext, we're leveraging the built-in support
            // in WPF to pump the messages via the Dispatcher.
            // See the following for additional details:
            //   http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx
            //   https://github.com/DotNetAnalyzers/StyleCopAnalyzers/pull/1362
            SynchronizationContext previousContext = SynchronizationContext.Current;
            try
            {
                var context = new DispatcherSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);

                DispatcherFrame dispatcherFrame = new DispatcherFrame();
                Task mainTask = MainAsync(args, cts.Token);
                mainTask.ContinueWith(task => dispatcherFrame.Continue = false);

                Dispatcher.PushFrame(dispatcherFrame);
                mainTask.GetAwaiter().GetResult();
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
开发者ID:umaranis,项目名称:StyleCopAnalyzers,代码行数:33,代码来源:Program.cs

示例9: 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

示例10: WhenProcessTimesOut_TaskIsCanceled

            public void WhenProcessTimesOut_TaskIsCanceled()
            {
                // Arrange
                const int expectedExitCode = 123;
                const int millisecondsForTimeout = 3 * 1000;
                const int millisecondsToSleep = 5 * 1000;
                const int expectedStandardOutputLineCount = 5;
                const int expectedStandardErrorLineCount = 3;

                // Act
                var pathToConsoleApp = typeof(DummyConsoleApp.Program).Assembly.Location;
                var arguments = String.Join(" ", expectedExitCode, millisecondsToSleep, expectedStandardOutputLineCount, expectedStandardErrorLineCount);
                var startInfo = new ProcessStartInfo(pathToConsoleApp, arguments);
                var cancellationToken = new CancellationTokenSource(millisecondsForTimeout).Token;
                var task = ProcessEx.RunAsync(startInfo, cancellationToken);

                // Assert
                Assert.IsNotNull(task);
                try
                {
                    var results = task.Result;
                    Assert.Fail("Timeout did not occur");
                }
                catch (AggregateException aggregateException)
                {
                    // expected
                    Assert.AreEqual(1, aggregateException.InnerExceptions.Count);
                    var innerException = aggregateException.InnerExceptions.Single();
                    Assert.IsInstanceOfType(innerException, typeof(OperationCanceledException));
                    var canceledException = innerException as OperationCanceledException;
                    Assert.IsNotNull(canceledException);
                    Assert.IsTrue(cancellationToken.IsCancellationRequested);
                }
                Assert.AreEqual(TaskStatus.Canceled, task.Status);
            }
开发者ID:vector-man,项目名称:RunProcessAsTask,代码行数:35,代码来源:ProcessExTests.cs

示例11: Application_Start

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var ts = new CancellationTokenSource();
            var host = Bootstrapper.Boot();
            host.Start(ts.Token);
            //            var bus = new FakeBus();
            //
            //            var storage = new EventStore(bus);
            //            var rep = new Repository<InventoryItem>(storage);
            //            var commands = new InventoryCommandHandlers(rep);
            //            bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
            //            bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
            //            bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
            //            bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
            //            bus.RegisterHandler<RenameInventoryItem>(commands.Handle);
            //            var detail = new InvenotryItemDetailView();
            //            bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
            //            bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
            //            bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
            //            bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
            //            bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
            //            var list = new InventoryListView();
            //            bus.RegisterHandler<InventoryItemCreated>(list.Handle);
            //            bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
            //            bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
            //            ServiceLocator.Bus = bus;
        }
开发者ID:trbngr,项目名称:m-r,代码行数:31,代码来源:Global.asax.cs

示例12: DatabaseBulkOperations

		public DatabaseBulkOperations(DocumentDatabase database, TransactionInformation transactionInformation, CancellationTokenSource tokenSource, CancellationTimeout timeout)
		{
			this.database = database;
			this.transactionInformation = transactionInformation;
			this.tokenSource = tokenSource;
			this.timeout = timeout;
		}
开发者ID:bbqchickenrobot,项目名称:ravendb,代码行数:7,代码来源:DatabaseBulkOperations.cs

示例13: CommandProcessor

        public CommandProcessor(ICommandProcessingStrategy processingStrategy,
                                ICommandQueue commandQueue)
        {
            _processingStrategy = processingStrategy;
            _commandQueue = commandQueue;

            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
            var task = new Task(
                () =>
                    {
                        while (!token.IsCancellationRequested)
                        {
                            var cmd = _commandQueue.Dequeue();
                            while (cmd != null)
                            {
                                _processingStrategy.ProcessCommand(cmd.Execute);
                                cmd = commandQueue.Dequeue();
                            }
                            Thread.Sleep(100);
                        }
                    },
                token,
                TaskCreationOptions.LongRunning);
            task.Start();
        }
开发者ID:naziway,项目名称:testtask,代码行数:26,代码来源:CommandProcessor.cs

示例14: BuildInGui

		/// <summary>
		/// Starts to run a build inside the SharpDevelop GUI.
		/// Only one build can run inside the GUI at one time.
		/// </summary>
		/// <param name="project">The project/solution to build.</param>
		/// <param name="options">The build options.</param>
		public static void BuildInGui(IBuildable project, BuildOptions options)
		{
			if (project == null)
				throw new ArgumentNullException("project");
			if (options == null)
				throw new ArgumentNullException("options");
			WorkbenchSingleton.AssertMainThread();
			if (guiBuildCancellation != null) {
				BuildResults results = new BuildResults();
				WorkbenchSingleton.StatusBar.SetMessage(Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
				BuildError error = new BuildError(null, Core.ResourceService.GetString("MainWindow.CompilerMessages.MSBuildAlreadyRunning"));
				results.Add(error);
				TaskService.Add(new Task(error));
				results.Result = BuildResultCode.MSBuildAlreadyRunning;
				if (options.Callback != null) {
					options.Callback(results);
				}
			} else {
				guiBuildCancellation = new CancellationTokenSource();
				IProgressMonitor progressMonitor = WorkbenchSingleton.StatusBar.CreateProgressMonitor(guiBuildCancellation.Token);
				guiBuildTrackedFeature = AnalyticsMonitorService.TrackFeature("ICSharpCode.SharpDevelop.Project.BuildEngine.Build");
				WorkbenchSingleton.StatusBar.SetMessage(StringParser.Parse("${res:MainWindow.CompilerMessages.BuildVerb}..."));
				ProjectService.RaiseEventBuildStarted(new BuildEventArgs(project, options));
				StartBuild(project, options,
				           new MessageViewSink(TaskService.BuildMessageViewCategory, progressMonitor, WorkbenchSingleton.StatusBar));
			}
		}
开发者ID:Altaxo,项目名称:Altaxo,代码行数:33,代码来源:BuildEngine.cs

示例15: GetQuickLocation

        public async Task<XLocation> GetQuickLocation()
        {
            Setup();

            var loc = new XLocation();

            _cancelSource = new CancellationTokenSource();

            await _geolocator.GetPositionAsync(1500, _cancelSource.Token, false)
                .ContinueWith(t =>
                {

                    if (t.IsCanceled || t.IsFaulted)
                    {
                        var x = new XLocation();
                        x.IsResolved = false;
                        x.Status = XPositionStatus.NotAvailble;
                        return x;
                    }
                        
                    loc.Latitude = t.Result.Latitude;
                    loc.Longitude = t.Result.Longitude;
                    loc.Accuracy = t.Result.Accuracy;
                    loc.Heading = t.Result.Heading;
                    loc.IsEnabled = true;
                    loc.IsResolved = true;
                    loc.Status = XPositionStatus.Ready;
                    return loc;
                }, _scheduler);
            return loc;
        }
开发者ID:jakkaj,项目名称:Xamling-Core,代码行数:31,代码来源:LocationTrackingSensor.cs


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