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


C# Threading.CancellationTokenSource类代码示例

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


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

示例1: CleanupTestLoadBalancers

        public async Task CleanupTestLoadBalancers()
        {
            ILoadBalancerService provider = CreateProvider();
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(60)));
            string queueName = CreateRandomLoadBalancerName();

            LoadBalancer[] allLoadBalancers = ListAllLoadBalancers(provider, null, cancellationTokenSource.Token).Where(loadBalancer => loadBalancer.Name.StartsWith(TestLoadBalancerPrefix, StringComparison.OrdinalIgnoreCase)).ToArray();
            int blockSize = 10;
            for (int i = 0; i < allLoadBalancers.Length; i += blockSize)
            {
                await provider.RemoveLoadBalancerRangeAsync(
                    allLoadBalancers
                        .Skip(i)
                        .Take(blockSize)
                        .Select(loadBalancer =>
                            {
                                Console.WriteLine("Deleting load balancer: {0}", loadBalancer.Name);
                                return loadBalancer.Id;
                            })
                        .ToArray(), // included to ensure the Console.WriteLine is only executed once per load balancer
                    AsyncCompletionOption.RequestCompleted,
                    cancellationTokenSource.Token,
                    null);
            }
        }
开发者ID:justinsaraceno,项目名称:openstack.net,代码行数:25,代码来源:UserLoadBalancerTests.cs

示例2: Renard

        public Renard(string portName)
        {
            this.serialPort = new SerialPort(portName, 57600);
            this.renardData = new byte[24];

            this.cancelSource = new System.Threading.CancellationTokenSource();
            this.firstChange = new System.Diagnostics.Stopwatch();

            this.senderTask = new Task(x =>
                {
                    while (!this.cancelSource.IsCancellationRequested)
                    {
                        bool sentChanges = false;

                        lock (lockObject)
                        {
                            if (this.dataChanges > 0)
                            {
                                this.firstChange.Stop();
                                //log.Info("Sending {0} changes to Renard. Oldest {1:N2}ms",
                                //    this.dataChanges, this.firstChange.Elapsed.TotalMilliseconds);
                                this.dataChanges = 0;
                                sentChanges = true;

                                SendSerialData(this.renardData);
                            }
                        }

                        if(!sentChanges)
                            System.Threading.Thread.Sleep(10);
                    }
                }, this.cancelSource.Token, TaskCreationOptions.LongRunning);

            Executor.Current.Register(this);
        }
开发者ID:HakanL,项目名称:animatroller,代码行数:35,代码来源:Renard.cs

示例3: Run

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Check the task cost
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            if (cost == BackgroundWorkCostValue.High)
            {
                return;
            }

            // Get the cancel token
            var cancel = new System.Threading.CancellationTokenSource();
            taskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };

            // Get deferral
            var deferral = taskInstance.GetDeferral();
            try
            {
                // Update Tile with the new xml
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(TileUpdaterTask.w10TileXml);

                TileNotification tileNotification = new TileNotification(xmldoc);
                TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication();
                tileUpdator.Update(tileNotification);
            }
            finally
            {
                deferral.Complete();
            }
        }
开发者ID:dfdcastro,项目名称:TDC2015,代码行数:34,代码来源:TileUpdaterTask.cs

示例4: EhLoaded

		private void EhLoaded(object sender, RoutedEventArgs e)
		{
			this._printerStatusCancellationTokenSource = new System.Threading.CancellationTokenSource();
			this._printerStatusCancellationToken = _printerStatusCancellationTokenSource.Token;

			System.Threading.Tasks.Task.Factory.StartNew(UpdatePrinterStatusGuiElements, _printerStatusCancellationToken);
		}
开发者ID:Altaxo,项目名称:Altaxo,代码行数:7,代码来源:PrintingControl.xaml.cs

示例5: OpenAsync

		public async Task OpenAsync()
		{
			tcs = new System.Threading.CancellationTokenSource();
			m_stream = await OpenStreamAsync();
			StartParser();
			MultiPartMessageCache.Clear();
		}
开发者ID:krasilies,项目名称:NmeaParser,代码行数:7,代码来源:NmeaDevice.cs

示例6: Execute

        public async void Execute(string token, string content)
        {
            Uri uri = new Uri(API_ADDRESS + path);

            var rootFilter = new HttpBaseProtocolFilter();

            rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

            HttpClient client = new HttpClient(rootFilter);
            //client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString());
            if(token != null)
                client.DefaultRequestHeaders.Add("x-access-token", token);

            System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);

            HttpResponseMessage response = null;
            if (requestType == GET)
            {
                try
                {
                    response = await client.GetAsync(uri).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }

            }else if (requestType == POST)
            {
                HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri);
                if (content != null)
                {
                    msg.Content = new HttpStringContent(content);
                    msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                }

                try
                {
                    response = await client.SendRequestAsync(msg).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }
            }

            if (response == null)
            {
                if (listener != null)
                    listener.onTaskCompleted(null, requestCode);
            }
            else
            {
                string answer = await response.Content.ReadAsStringAsync();

                if(listener != null)
                    listener.onTaskCompleted(answer, requestCode);
            }
        }
开发者ID:francisco-maciel,项目名称:FEUP-CMOV_StockQuotes,代码行数:60,代码来源:APIRequest.cs

示例7: TestGetHome

 public async Task TestGetHome()
 {
     IQueueingService provider = CreateProvider();
     CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(10)));
     HomeDocument document = await provider.GetHomeAsync(cancellationTokenSource.Token);
     Assert.IsNotNull(document);
     Console.WriteLine(JsonConvert.SerializeObject(document, Formatting.Indented));
 }
开发者ID:justinsaraceno,项目名称:openstack.net,代码行数:8,代码来源:UserQueuesTests.cs

示例8: CancellationCallbackInfo

 internal CancellationCallbackInfo(Action<object> callback, object stateForCallback, SynchronizationContext targetSyncContext, ExecutionContext targetExecutionContext, System.Threading.CancellationTokenSource cancellationTokenSource)
 {
     this.Callback = callback;
     this.StateForCallback = stateForCallback;
     this.TargetSyncContext = targetSyncContext;
     this.TargetExecutionContext = targetExecutionContext;
     this.CancellationTokenSource = cancellationTokenSource;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:CancellationCallbackInfo.cs

示例9: ClassCleanup

 public static void ClassCleanup()
 {
     IDatabaseService provider = UserDatabaseTests.CreateProvider();
     using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(600))))
     {
         provider.RemoveDatabaseInstanceAsync(_instance.Id, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null).Wait();
     }
 }
开发者ID:charlyraffellini,项目名称:openstack.net,代码行数:8,代码来源:UserDatabaseUserTests.cs

示例10: Launcher_BuildUpdated

        void Launcher_BuildUpdated(Client.Launcher.BuildUpdatedEventArgs e)
        {
            HashSet<Settings.IDatFile> dats = new HashSet<Settings.IDatFile>();
            List<Settings.IAccount> accounts = new List<Settings.IAccount>();

            //only accounts with a unique dat file need to be updated

            foreach (ushort uid in Settings.Accounts.GetKeys())
            {
                var a = Settings.Accounts[uid];
                if (a.HasValue && (a.Value.DatFile == null || dats.Add(a.Value.DatFile)))
                {
                    accounts.Add(a.Value);
                }
            }

            if (accounts.Count > 0)
            {
                System.Threading.CancellationTokenSource cancel = new System.Threading.CancellationTokenSource(3000);

                try
                {
                    this.BeginInvoke(new MethodInvoker(
                        delegate
                        {
                            BeforeShowDialog();
                            try
                            {
                                activeWindows++;
                                using (formUpdating f = new formUpdating(accounts, true, true))
                                {
                                    f.Shown += delegate
                                    {
                                        cancel.Cancel();
                                    };
                                    f.ShowDialog(this);
                                }
                            }
                            finally
                            {
                                activeWindows--;
                            }
                        }));
                }
                catch { }

                try
                {
                    cancel.Token.WaitHandle.WaitOne();
                }
                catch (Exception ex)
                {
                    ex = ex;
                }

                e.Update(accounts);
            }
        }
开发者ID:Healix,项目名称:Gw2Launcher,代码行数:58,代码来源:formMain.cs

示例11: SymbolProcessorTaskWorkDiconnectCancellationTest

 public bool SymbolProcessorTaskWorkDiconnectCancellationTest()
 {
     if (null == _cts)
         _cts = new System.Threading.CancellationTokenSource();
     Disconnect();
     base.OnNewDataReceived = SymbolProcessorTaskWorkCancellationTest;
     dataQueue.CompleteAdding();
     SymbolProcessorTaskWork();
     return _dataReceived;
 }
开发者ID:showtroylove,项目名称:MarketDataConsumer,代码行数:10,代码来源:MarketDataTests.cs

示例12: ZXingSurfaceView

	    protected ZXingSurfaceView(IntPtr javaReference, JniHandleOwnership transfer) 
            : base(javaReference, transfer) 
        {
            lastPreviewAnalysis = DateTime.Now.AddMilliseconds(options.InitialDelayBeforeAnalyzingFrames);

            this.surface_holder = Holder;
            this.surface_holder.AddCallback(this);
            this.surface_holder.SetType(SurfaceType.PushBuffers);

            this.tokenSource = new System.Threading.CancellationTokenSource();
	    }
开发者ID:jerryshen1987,项目名称:ZXing.Net.Mobile,代码行数:11,代码来源:ZXingSurfaceView.cs

示例13: OpenAsync

		/// <summary>
		/// Opens the device connection.
		/// </summary>
		/// <returns></returns>
		public async Task OpenAsync()
		{
			lock (m_lockObject)
			{
				if (IsOpen) return;
				IsOpen = true;
			}
			m_cts = new System.Threading.CancellationTokenSource();
			m_stream = await OpenStreamAsync();
			StartParser();
			MultiPartMessageCache.Clear();
		}
开发者ID:rainlabs-eu,项目名称:NmeaParser,代码行数:16,代码来源:NmeaDevice.cs

示例14: shouldCancelDuringBuild

        public async Task shouldCancelDuringBuild()
        {
            var cancellationTestee = new PipelineManager();
            var canceller = new System.Threading.CancellationTokenSource();
            var progressReporter = new PipelineProgress(canceller.Cancel, 50, false);

            var result = await cancellationTestee.BuildPipelineAsync(this.scheme, canceller.Token, progressReporter, new TestSubject());

            var refinedResults = result.Select(r => r.Outcome).ToArray();

            Assert.IsTrue(refinedResults.Contains(StepBuildResults.Cancelled) && refinedResults.Contains(StepBuildResults.Completed), "Token may have expirec before the build took place.\nResults are:\n" + refinedResults.PrintContentsToString(Environment.NewLine));
        }
开发者ID:kurzatem,项目名称:TheHUtil,代码行数:12,代码来源:PipelineManagerTests.cs

示例15: LoadUser

 public static HubblUser LoadUser()
 {
     var source = new System.Threading.CancellationTokenSource (10000);
     var token = source.Token;
     try {
         var file = FileSystem.Current.LocalStorage.GetFileAsync ("user", token).Result;
         var sUser = file.ReadAllTextAsync ().Result;
         var user = JsonConvert.DeserializeObject<HubblUser>(sUser);
         user.IsHub = false;
         return user;
     } catch (Exception) {
         return null;
     }
 }
开发者ID:mesenev,项目名称:hubbl,代码行数:14,代码来源:HubblUser.cs


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