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


C# CancellationTokenSource.Dispose方法代码示例

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


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

示例1: getImagesButton_Click

		private async void getImagesButton_Click(object sender, EventArgs e) {
			// start the timer for updating the UI
			progressTimer.Enabled = true;
			cancelButton.Enabled = true;
			getImagesButton.Enabled = false;
			// Get and process all images, but don't block the UI thread
			try {
				// Create to get a cancellation token for the job
				source = new CancellationTokenSource();
				// Create a job counters object, to be updated by the async task
				counters = new MongoUniversityPlugin.JobCounters();
				int count = await (this.Plugin as MongoUniversityPlugin).GetImages(source.Token, counters);
				// this will wait for completion of the above (it's async though!)
				countTextBox.Text = count.ToString();
			}
			catch (OperationCanceledException ex) {
				MessageBox.Show("The operation was cancelled");
				source.Dispose();
			}
			finally {
				// stop the timer
				progressTimer.Enabled = false;
				cancelButton.Enabled = false;
				getImagesButton.Enabled = true;
				UpdateCounters();
			}

		}
开发者ID:bobstoned,项目名称:MongoExplorer,代码行数:28,代码来源:MongoUniPluginControl.cs

示例2: Main

        static void Main()
        {
            Console.WriteLine("Основной поток запущен");

            // Объект источника признаков отмены
            CancellationTokenSource cancelTokSSrc = new CancellationTokenSource();

            // Запустить задачу, передав ей признак отмены
            Task tsk = Task.Factory.StartNew(MyTask, cancelTokSSrc.Token, cancelTokSSrc.Token);

            Thread.Sleep(2000);
            try
            {
                // отменить задачу
                cancelTokSSrc.Cancel();
                tsk.Wait();
            }
            catch (AggregateException exc)
            {
                if (tsk.IsCanceled)
                    Console.WriteLine("Задача tsk отменена");
            }
            finally
            {
                tsk.Dispose();
                cancelTokSSrc.Dispose();
            }

            Console.WriteLine("Основной поток завершен");
            Console.ReadLine();
        }
开发者ID:kokushkin,项目名称:TestRepository,代码行数:31,代码来源:Program.cs

示例3: cleanUp

        private static void cleanUp(List<Task> tasks, CancellationTokenSource cancelToken)
        {
            // cancel tasks
            cancelToken.Cancel();

            try
            {
                // wait until all tasks are finished
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException e)
            {
                foreach (var inner in e.InnerExceptions)
                {
                    if (inner is TaskCanceledException)
                        continue;
                    else
                        Console.WriteLine("Exception while stopping: {0} {1}", inner.GetType().Name, inner.Message);
                }
            }
            finally
            {
                tasks = null;
                cancelToken.Dispose();
            }
        }
开发者ID:jenyayel,项目名称:ws-mq-latency-tester,代码行数:26,代码来源:Program.cs

示例4: Main

        static void Main(string[] args) {

            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(1000);

            Stopwatch watch = new Stopwatch();
            watch.Start();

            InternalGetIntAsync(cts.Token).ContinueWith((task) => {

                Console.WriteLine("Elapsed time: {0}ms", watch.Elapsed.TotalMilliseconds);
                watch.Stop();

                //We get the response. 
                //Dispose of the CancellationTokenSource
                //so that it is not going to signal.
                cts.Dispose();

                if (task.Status == TaskStatus.RanToCompletion) {

                    Console.WriteLine(task.Result);
                }
                else if (task.Status == TaskStatus.Canceled) {

                    Console.WriteLine("The task has been canceled.");
                }
                else {
                    Console.WriteLine("An error has been occurred. Details:");
                    Console.WriteLine(task.Exception.InnerException.Message);
                }
            });

            Console.ReadLine();
        }
开发者ID:tugberkugurlu,项目名称:ProWebAPI.Samples,代码行数:34,代码来源:Program.cs

示例5: DownloadStringAsync

 public async static Task<string> DownloadStringAsync(string url)
 {
     var tcs = new CancellationTokenSource();
     var client = new HttpClient();
     lock (lck)
     {
         cancelTokens.Add(tcs);
     }
     string res = null;
     try
     {
         var x = await client.GetAsync(url, tcs.Token);
         res = await x.Content.ReadAsStringAsync();
     }
     catch (Exception e)
     {
        
     }
     finally
     {
         client.Dispose();
         lock (lck)
         {
             cancelTokens.Remove(tcs);
         }
         tcs.Dispose();
     }
     return res;
 }
开发者ID:3ricguo,项目名称:xiami_downloader,代码行数:29,代码来源:NetAccess.cs

示例6: DoSomeLongRunningTask

        private void DoSomeLongRunningTask(int operationId, CancellationTokenSource cts)
        {
            // Kick off the long running operation in the background
            Task.Run(async () =>
            {
                // When the cts trips we're going to call the client back and tell them the operation is cancelled
                CancellationTokenRegistration registration = cts.Token.Register(() => Clients.Caller.cancelled(operationId));

                // Pretend to something long running
                await Task.Delay(5000);

                // Don't call complete if we're cancelled
                if (!cts.IsCancellationRequested)
                {
                    Clients.Caller.complete(operationId);
                }

                // Don't leak registrations
                registration.Dispose();

                // Remove it from the list of pending operations
                _pendingOperations.TryRemove(operationId, out cts);

                // Might not need this but lets not forget to dispose anything
                cts.Dispose();
            });
        }
开发者ID:haseebshujja,项目名称:Samples,代码行数:27,代码来源:OperationHub.cs

示例7: button2_Click

        private void button2_Click(object sender, EventArgs e)
        {
            Service service = new Service();
            int expectedDuration = 10;            
            ToOutput("[Started] Worker with progress ({0} seconds)", expectedDuration);

            m_cts = new CancellationTokenSource();            

            button2.Enabled = false;
            Task.Factory.StartNew(() => service.DoWithProgress(expectedDuration,
                progress =>
                {
                    Invoke((Action) delegate
                    {
                        ToOutput("[Progress] Worker with progress ({0})", progress);
                    });
                }, m_cts.Token), m_cts.Token)
                .ContinueWith(data =>
                {
                    if (m_cts.IsCancellationRequested)
                        ToOutput("[Cancelled] Worker with progress");
                    ToOutput("[Completed] Worker with progress");
                    m_cts.Dispose();
                    m_cts = null;
                    button2.Enabled = true;
                }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
        }
开发者ID:constructor-igor,项目名称:TechSugar,代码行数:27,代码来源:Main.cs

示例8: Main

        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            // Create an opportunity for the user to cancel.
            Task.Run(() =>
            {
                if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C')
                    cts.Cancel();
            });

            ObjectPool<TestClass> pool = new ObjectPool<TestClass>(() => new TestClass());

            // Create a high demand for MyClass objects.
            Parallel.For(0, 1000000, (i, loopState) =>
            {

                using(TestClass mc = pool.GetResource())
                {
                    Console.CursorLeft = 0;
                    // This is the bottleneck in our application. All threads in this loop
                    // must serialize their access to the static Console class.
                    Console.WriteLine("{0:####.####}", mc.GetValue(i));
                    // pool.PoolResource(mc); alternative to implementing repool in the dispose method
                }

                if (cts.Token.IsCancellationRequested)
                    loopState.Stop();

            });
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            cts.Dispose();
        }
开发者ID:chivandikwa,项目名称:ObjectPool,代码行数:34,代码来源:Program.cs

示例9: Main

        public static int Main(string[] args)
        {
            Logger.Info("Application started.");

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledApplicationException;

            Executer = new CodeExecuter();
            TokenSource = new CancellationTokenSource();

            try
            {
                var task = Task.Factory.StartNew(ProcessQueue, TokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                task.ContinueWith(OnTaskFaulted, TaskContinuationOptions.OnlyOnFaulted);

                task.Wait();

                Logger.Debug("Task finished.");
            }
            catch (RedisException ex)
            {
                Logger.ErrorException("An error occured while attempting to access Redis.", ex);
            }
            finally
            {
                if (TokenSource != null)
                {
                    TokenSource.Cancel();
                    TokenSource.Dispose();
                }
            }

            Logger.Info("Application ending.");

            return -1; // Return a non-zero code so AppHarbor restarts the worker
        }
开发者ID:plurby,项目名称:Compilify,代码行数:35,代码来源:Program.cs

示例10: Main

        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(1000);

            AsyncFactory.GetIntAsync(cts.Token).ContinueWith((task) => {
                //We get the response.
                //So dispose the CancellationTokenSource
                //so that it is not going to signal.
                cts.Dispose();

                if (task.Status == TaskStatus.RanToCompletion)
                {
                    Console.WriteLine(task.Result);
                }
                else if (task.Status == TaskStatus.Canceled)
                {
                    Console.WriteLine("The task has been canceled.");
                }
                else
                {
                    Console.WriteLine("An error has been occurred. Details:");
                    Console.WriteLine(task.Exception.InnerException.Message);
                }
            });

            Console.ReadLine();
        }
开发者ID:hctan,项目名称:AsyncTest,代码行数:28,代码来源:Program.cs

示例11: Main

        static void Main(string[] args)
        {
            var verbose = args.Length > 0 && args[0] == "-v";

            var cts = new CancellationTokenSource ();

            // trapping Ctrl+C as exit signal!
            Console.CancelKeyPress += (s, e) =>
                                      {
                                          e.Cancel = true;
                                          cts.Cancel ();
                                      };

            Console.WriteLine ("Starting Titanic Broker in {0} - mode.\n\n", verbose ? "verbose" : "silent");

            using (var titanic = new TitanicBroker (new TitanicMemoryIO ()))
            {
                if (verbose)
                    titanic.LogInfoReady += (s, e) => PrintMessage (e.Info);

                try
                {
                    Task.Factory.StartNew (() => titanic.Run (), cts.Token).Wait (cts.Token);
                }
                catch (AggregateException e)
                {
                    Console.WriteLine (e.Flatten ());
                }
                finally
                {
                    cts.Dispose ();
                }
            }
        }
开发者ID:wangkai2014,项目名称:netmq,代码行数:34,代码来源:TitanicBrokerMain.cs

示例12: AsyncError

        public async void AsyncError()
        {
            CancellationTokenSource source = new CancellationTokenSource();
            var token = source.Token;
            int i = 0;

            var t = Task.Factory.StartNew(() =>
            {

                token.Register(() => { Debug.WriteLine("End"); }, true);

                while (i++ < 20 && !token.IsCancellationRequested)
                {
                    Debug.WriteLine(i.ToString());
                    Thread.Sleep(100);
                }
            }, token, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

            var t1 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(500);
                source.Cancel();
            });

            try
            {
                Task.WaitAll(t, t1);
            }
            finally
            {
                source.Dispose();
            }
        }
开发者ID:constructor-igor,项目名称:TechSugar,代码行数:33,代码来源:NUnitIssue924.cs

示例13: CancellationTokenSource

        // This method evaluates the expression asynchronously.
        // This method should return immediately after it has started the expression evaluation. 
        // When the expression is successfully evaluated, an IDebugExpressionEvaluationCompleteEvent2 
        // must be sent to the IDebugEventCallback2 event callback
        int IDebugExpression2.EvaluateAsync(enum_EVALFLAGS dwFlags, IDebugEventCallback2 pExprCallback) {
            _tokenSource = new CancellationTokenSource();

            _frame.StackFrame.ExecuteTextAsync(_expression, _tokenSource.Token)
                .ContinueWith(p => {
                    try {
                        IDebugProperty2 property;
                        if (p.Exception != null && p.Exception.InnerException != null) {
                            property = new AD7EvalErrorProperty(p.Exception.InnerException.Message);
                        } else if (p.IsCanceled) {
                            property = new AD7EvalErrorProperty("Evaluation canceled");
                        } else if (p.IsFaulted || p.Result == null) {
                            property = new AD7EvalErrorProperty("Error");
                        } else {
                            property = new AD7Property(_frame, p.Result);
                        }

                        _tokenSource.Token.ThrowIfCancellationRequested();
                        _frame.Engine.Send(
                            new AD7ExpressionEvaluationCompleteEvent(this, property),
                            AD7ExpressionEvaluationCompleteEvent.IID,
                            _frame.Engine,
                            _frame.Thread);
                    } finally {
                        _tokenSource.Dispose();
                        _tokenSource = null;
                    }
                }, _tokenSource.Token);

            return VSConstants.S_OK;
        }
开发者ID:paladique,项目名称:nodejstools,代码行数:35,代码来源:UncalculatedAD7Expression.cs

示例14: CreateTask

        public CancellationTokenSource CreateTask( long agentId )
        {
            CancellationTokenSource source = new CancellationTokenSource();
            var task = new Task( async () =>
            {
                while( !source.Token.IsCancellationRequested )
                {
                    try
                    {
                        using( AgentServiceClient client = new AgentServiceClient() )
                        {
                            await client.HandshakeAsync( agentId );
                            while( !source.Token.IsCancellationRequested )
                            {
                                Thread.Sleep( 1000 );
                                await client.DoOperationAsync();
                            }
                        }
                    }
                    catch
                    {
                        Thread.Sleep( 1000 );
                    }
                }

                source.Dispose();
            }, source.Token );
            task.Start();
            return source;
        }
开发者ID:timba,项目名称:async-ef-performance-test,代码行数:30,代码来源:AgentsControl.cs

示例15: GetManyAsync

        public Task<GetManyResult> GetManyAsync(
            Guid clientGuid,
            string domain,
            FactTreeMemento tree,
            Dictionary<long, long> pivotIds,
            int timeoutSeconds)
        {
            GetManyResult result = GetManyInternal(clientGuid, domain, tree, pivotIds);
            if (timeoutSeconds > 0 && !result.Tree.Facts.Any())
            {
                CancellationTokenSource cancellation = new CancellationTokenSource();
                int session = _messageBus.Register(
                    domain,
                    result.LocalPivotIds,
                    clientGuid,
                    () => cancellation.Cancel());
                return Task
                    .Delay(timeoutSeconds * 1000, cancellation.Token)
                    .ContinueWith(t => t.IsCanceled
                        ? GetManyInternal(clientGuid, domain, tree, pivotIds)
                        : result)
                    .ContinueWith(t =>
                    {
                        _messageBus.Unregister(session);
                        cancellation.Dispose();
                        return t.Result;
                    });
            }

            return Task.FromResult(result);
        }
开发者ID:wuttic,项目名称:CorrespondenceDistributor,代码行数:31,代码来源:DistributorService.cs


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