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


C# Task.ContinueWith方法代码示例

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


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

示例1: Validate

        public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
        {
            var tasks = new List<Task<IYubicoResponse>>();
            var cancellation = new CancellationTokenSource();

            foreach (var url in urls)
            {
                var thisUrl = url;
                var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
                task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                tasks.Add(task);
                task.Start();
            }

            while (tasks.Count != 0)
            {
                // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
                var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
                var task = tasks[completed];
                tasks.Remove(task);
                if (task.Result != null)
                {
                    cancellation.Cancel();
                    return task.Result;
                }
            }

            return null;
        }
开发者ID:Yubico,项目名称:yubico-dotnet-client,代码行数:29,代码来源:YubicoValidate.cs

示例2: ConnectToRabbit

        private void ConnectToRabbit(ConnectionFactory connectionfactory, string rabbitMqExchangeName)
        {
            if (1 == Interlocked.Exchange(ref _resource, 1))
            {
                return;
            }

            _rabbitConnection = new RabbitConnection(connectionfactory, rabbitMqExchangeName);
            _rabbitConnection.OnMessage( wrapper => OnReceived(wrapper.Key, wrapper.Id, wrapper.Messages));

            _rabbitConnectiontask = _rabbitConnection.StartListening();
            _rabbitConnectiontask.ContinueWith(
                t =>
                    {
                        Interlocked.Exchange(ref _resource, 0);
                        ConnectToRabbit(connectionfactory, rabbitMqExchangeName);
                    }
                );
            _rabbitConnectiontask.ContinueWith(
                  t =>
                  {
                      Interlocked.Exchange(ref _resource, 0);
                      ConnectToRabbit(connectionfactory, rabbitMqExchangeName);
                  },
                  CancellationToken.None,
                  TaskContinuationOptions.OnlyOnFaulted,
                  TaskScheduler.Default
            );

        }
开发者ID:mickdelaney,项目名称:SignalR.RabbitMq,代码行数:30,代码来源:RabbitMqMessageBus.cs

示例3: OnMouseClick

            protected override void OnMouseClick(MouseEventArgs e) {
                if(_cts != null) {
                    _cts.Cancel();
                    _cts = null;
                }
                else {
                    Text = @"Operation running";
                    _cts = new CancellationTokenSource();

                    var task = new Task<int>(() => Sum(2000, _cts.Token), _cts.Token);
                    task.Start();

                    // UI 작업에서는 SynchronizationTaskScheduler를 사용해야 합니다.
                    task.ContinueWith(antecedent => Text = "Result:" + antecedent.Result,
                                      CancellationToken.None,
                                      TaskContinuationOptions.OnlyOnRanToCompletion,
                                      _syncContextTaskScheduler);

                    task.ContinueWith(antecedent => Text = "Operation canceled",
                                      CancellationToken.None,
                                      TaskContinuationOptions.OnlyOnCanceled,
                                      _syncContextTaskScheduler);

                    task.ContinueWith(antecedent => Text = "Operation faulted",
                                      CancellationToken.None,
                                      TaskContinuationOptions.OnlyOnFaulted,
                                      _syncContextTaskScheduler);
                }
                base.OnMouseClick(e);
            }
开发者ID:debop,项目名称:NFramework,代码行数:30,代码来源:TaskSchedulerTestCase.cs

示例4: StartAnalysis

        public void StartAnalysis()
        {
            var task = new Task<StoreReport>(RunAnalysis);
            task.ContinueWith(t => t != null ? (Report = new StoreAnalysisModel(t.Result)) : null,CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
            task.ContinueWith(t => AnalyzerException = t.Exception,CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
            task.Start();

        }
开发者ID:GTuritto,项目名称:BrightstarDB,代码行数:8,代码来源:StoreAnalyzerViewModel.cs

示例5: HandleOnCompleted

		internal static void HandleOnCompleted (Task task, Action continuation)
		{
			var scontext = SynchronizationContext.Current;
			if (scontext != null)
				task.ContinueWith (l => scontext.Post (cont => ((Action) cont) (), continuation), TaskContinuationOptions.ExecuteSynchronously);
			else
				task.ContinueWith (l => continuation (), TaskContinuationOptions.ExecuteSynchronously);
		}
开发者ID:jlundstocholm,项目名称:mono,代码行数:8,代码来源:TaskAwaiter.cs

示例6: HandleOnCompleted

		internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext)
		{
			if (continueOnSourceContext && SynchronizationContext.Current != null) {
				task.ContinueWith (new SynchronizationContextContinuation (continuation, SynchronizationContext.Current));
			} else {
				task.ContinueWith (new ActionContinuation (continuation));
			}
		}
开发者ID:robert-j,项目名称:mono-fork,代码行数:8,代码来源:TaskAwaiter.cs

示例7: HandleOnCompleted

		internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext, InstanceReference instanceReference, IAsyncSetThis thisSetter)
		{
			if (continueOnSourceContext && SynchronizationContext.Current != null) {
                task.ContinueWith(new SynchronizationContextContinuation(continuation, SynchronizationContext.Current, instanceReference, thisSetter));
			} else {
				task.ContinueWith (new ActionContinuation (continuation));
			}
		}
开发者ID:nguyenkien,项目名称:api,代码行数:8,代码来源:TaskAwaiter.cs

示例8: button2_Click

 private void button2_Click(object sender, EventArgs e)
 {
     Coder coder = new Coder(_point_State_color, new TimeSpan(0,2,0));
     CancellationToken token = _tokenSrcCancel.Token;
     Task task = new Task( () => coder.Code(token), token);
     task.ContinueWith(coding_exception_handler, TaskContinuationOptions.OnlyOnFaulted);
     task.ContinueWith(coding_done_handler, TaskContinuationOptions.OnlyOnRanToCompletion);
     task.Start();
 }
开发者ID:vicmatmar,项目名称:TestAutoit,代码行数:9,代码来源:Form1.cs

示例9: HandleOnCompleted

		internal static void HandleOnCompleted (Task task, Action continuation, bool continueOnSourceContext)
		{
			if (continueOnSourceContext && SynchronizationContext.Current != null) {
				// Capture source context
				var ctx = SynchronizationContext.Current;
				task.ContinueWith (l => ctx.Post (cont => ((Action) cont) (), continuation), TaskContinuationOptions.ExecuteSynchronously);
			} else {
				task.ContinueWith ((l, cont) => ((Action) cont) (), continuation, TaskContinuationOptions.ExecuteSynchronously);
			}
		}
开发者ID:kazol4433,项目名称:mono,代码行数:10,代码来源:TaskAwaiter.cs

示例10: ContinuationTask

        static void ContinuationTask()
        {
            Task t1 = new Task(DoOnFirst);
              Task t2 = t1.ContinueWith(DoOnSecond);
              Task t3 = t1.ContinueWith(DoOnSecond);
              Task t4 = t2.ContinueWith(DoOnSecond);
              Task t5 = t1.ContinueWith(DoOnError, TaskContinuationOptions.OnlyOnFaulted);
              t1.Start();

              Thread.Sleep(5000);
        }
开发者ID:CNinnovation,项目名称:ParallelProgrammingFeb2016,代码行数:11,代码来源:Program.cs

示例11: Main

        static void Main(string[] args)
        {
            // create a cancellation token source
            CancellationTokenSource tokenSource
                = new CancellationTokenSource();

            // create the antecedent task
            Task task = new Task(() => {
                // write out a message
                Console.WriteLine("Antecedent running");
                // wait indefinately on the token wait handle
                tokenSource.Token.WaitHandle.WaitOne();
                // handle the cancellation exception
                tokenSource.Token.ThrowIfCancellationRequested();
            }, tokenSource.Token);

            // create a selective continuation
            Task neverScheduled = task.ContinueWith(antecedent => {
                // write out a message
                Console.WriteLine("This task will never be scheduled");
            }, tokenSource.Token);

            // create a bad selective contination
            Task badSelective = task.ContinueWith(antecedent => {
                // write out a message
                Console.WriteLine("This task will never be scheduled");
            }, tokenSource.Token, TaskContinuationOptions.OnlyOnCanceled,
            TaskScheduler.Current);

            // create a good selective contiuation
            Task continuation = task.ContinueWith(antecedent => {
                // write out a message
                Console.WriteLine("Continuation running");
            }, TaskContinuationOptions.OnlyOnCanceled);

            // start the task
            task.Start();

            // prompt the user so they can cancel the token
            Console.WriteLine("Press enter to cancel token");
            Console.ReadLine();
            // cancel the token source
            tokenSource.Cancel();

            // wait for the good continuation to complete
            continuation.Wait();

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:51,代码来源:Listing_07.cs

示例12: Main

        static void Main(string[] args)
        {
            // get the processor count for the system
            int procCount = System.Environment.ProcessorCount;

            // create a custom scheduler
            CustomScheduler scheduler = new CustomScheduler(procCount);

            Console.WriteLine("Custom scheduler ID: {0}", scheduler.Id);
            Console.WriteLine("Default scheduler ID: {0}", TaskScheduler.Default.Id);

            // create a cancellation token source
            CancellationTokenSource tokenSource = new CancellationTokenSource();

            // create a task
            Task task1 = new Task(() => {

                Console.WriteLine("Task {0} executed by scheduler {1}",
                        Task.CurrentId, TaskScheduler.Current.Id);

                // create a child task - this will use the same
                // scheduler as its parent
                Task.Factory.StartNew(() => {
                    Console.WriteLine("Task {0} executed by scheduler {1}",
                        Task.CurrentId, TaskScheduler.Current.Id);
                });

                // create a child and specify the default scheduler
                Task.Factory.StartNew(() => {
                    Console.WriteLine("Task {0} executed by scheduler {1}",
                        Task.CurrentId, TaskScheduler.Current.Id);
                }, tokenSource.Token, TaskCreationOptions.None, TaskScheduler.Default);

            });

            // start the task using the custom scheduler
            task1.Start(scheduler);

            // create a continuation - this will use the default scheduler
            task1.ContinueWith(antecedent => {
                Console.WriteLine("Task {0} executed by scheduler {1}",
                    Task.CurrentId, TaskScheduler.Current.Id);
            });

            // create a continuation using the custom scheduler
            task1.ContinueWith(antecedent => {
                Console.WriteLine("Task {0} executed by scheduler {1}",
                    Task.CurrentId, TaskScheduler.Current.Id);
            }, scheduler);
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:50,代码来源:Listing_22.cs

示例13: Main

        static void Main(string[] args)
        {
            // create a token source
            CancellationTokenSource tokenSource
                = new CancellationTokenSource();

            // create the antecedent task
            Task<int> task1 = new Task<int>(() => {
                // wait for the token to be cancelled
                tokenSource.Token.WaitHandle.WaitOne();
                // throw the cancellation exception
                tokenSource.Token.ThrowIfCancellationRequested();
                // return the result - this code will
                // never be reached but is required to
                // satisfy the compiler
                return 100;
            }, tokenSource.Token);

            // create a continuation
            // *** BAD CODE ***
            Task task2 = task1.ContinueWith((Task<int> antecedent) => {
                // read the antecedent result without checking
                // the status of the task
                Console.WriteLine("Antecedent result: {0}", antecedent.Result);
            });

            // create a continuation, but use a token
            Task task3 = task1.ContinueWith((Task<int> antecedent) => {
                // this task will never be executed
            }, tokenSource.Token);

            // create a continuation that checks the status
            // of the antecedent
            Task task4 = task1.ContinueWith((Task<int> antecedent) => {
                if (antecedent.Status == TaskStatus.Canceled) {
                    Console.WriteLine("Antecedent cancelled");
                } else {
                    Console.WriteLine("Antecedent Result: {0}", antecedent.Result);
                }
            });

            // prompt the user and cancel the token
            Console.WriteLine("Press enter to cancel token");
            Console.ReadLine();
            tokenSource.Cancel();

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:50,代码来源:Inconsistent_Cancellation.cs

示例14: Main

        static void Main(string[] args)
        {
            Class1 d = new Class1(Path.GetFullPath(System.Environment.CurrentDirectory + "/../"));
            Console.Read();
            var Start = new Task(() => start());
            Start.ContinueWith(t => Contiute1_1())
                .ContinueWith(t => Contiute1_2());

            var task2_1 = Start.ContinueWith(t => Contiute2_1());
            var task2_2 = task2_1.ContinueWith(t => Contiute2_2());

            Start.RunSynchronously();
            Console.WriteLine("end");
            Console.ReadKey();
        }
开发者ID:luqizheng,项目名称:lb_releaseIt,代码行数:15,代码来源:Program.cs

示例15: Add

 public void Add(ITextFile textFile)
 {
     Task task = new Task(() => ProduceFrom(textFile));
     task.ContinueWith(HandleFileProcessed);
     producerTasks.TryAdd(task, textFile);
     task.Start();
 }
开发者ID:peterchase,项目名称:parallel-workshop,代码行数:7,代码来源:BlockingMultiFileCharacterCounter.cs


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