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


C# TaskFactory.ContinueWhenAll方法代码示例

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


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

示例1: Begin_Click

 private void Begin_Click(object sender, EventArgs e)
 {
     Begin.Text = "开始...";
     Begin.Enabled = false;
     start = true;
     List<Task> listTask = new List<Task>();
     TaskFactory tskf = new TaskFactory();
     var controls = groupBox.Controls;
     foreach (var control in controls)
     {
         if (control.GetType() != typeof(Label))
         {
             continue;
         }
         var label = control as Label;
         listTask.Add(tskf.StartNew(new Action(() =>
         {
             while (start)
             {
                 Thread.Sleep(200);
                 var text = GeNum(label);
                 UpdateLabl(label, text);
                 //Console.WriteLine("label:[{0}],value:[{1}]", label.Name, text);
             }
         })));
     }
     tskf.ContinueWhenAll(listTask.ToArray(), (rest) => { ShowMessage(); });
     //MessageBox.Show("主线程结束了。。。", "结果");
     Thread.Sleep(1000);
     End.Enabled = true;
 }
开发者ID:s455016457,项目名称:study,代码行数:31,代码来源:Form1.cs

示例2: Run4Common

        private static void Run4Common()
        {
            var tasksCount = 10;
            _log.Debug("任务调度开始……");

            var taskFactory = new TaskFactory();
            var cts = new CancellationTokenSource();
            var tasks = new Task<string>[10];

            for (var i = 0; i < tasksCount; i++)
            {
                var i1 = i;
                tasks[i] =
                taskFactory.StartNew(() => Handler(new TaskArgs
                {
                    CancellationToken = cts.Token,
                    Name = i1.ToString(CultureInfo.InvariantCulture)
                }), cts.Token);
            }

            //TaskContinuationOptions.None 有异常会 中断。。。。
            taskFactory.ContinueWhenAll(tasks, CompleteCallback, TaskContinuationOptions.None);

            _log.Debug("任务调度完成……");

        }
开发者ID:ngnono,项目名称:NGnono.Doubts,代码行数:26,代码来源:Program.cs

示例3: Main

    public static void Main(){
        Task parent = new Task(() => 
	    {
                var cts = new CancellationTokenSource ();
                var tf  = new TaskFactory<Int32> (cts.Token, 
						  TaskCreationOptions.AttachedToParent,
                                                  TaskContinuationOptions.ExecuteSynchronously, 
						  TaskScheduler.Default);

                // This task creates and starts 3 child tasks
                var childTasks = new[] {
                    tf.StartNew(() => Sum(cts.Token, 10000)),
                    tf.StartNew(() => Sum(cts.Token, 20000)),
                    tf.StartNew(() => Sum(cts.Token, Int32.MaxValue))  // Too big, throws OverflowException
                };

                // If any of the child tasks throw, cancel the rest of them
                for (Int32 task = 0; task < childTasks.Length; task++)
                    childTasks[task].ContinueWith (t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

                // When all children are done, get the maximum value returned from the
                // non-faulting/canceled tasks. Then pass the maximum value to another
                // task that displays the maximum result
                tf.ContinueWhenAll (childTasks, completedTasks => completedTasks.Where(t => t.Status == TaskStatus.RanToCompletion).Max(t => t.Result), 
                                    CancellationToken.None)
                .ContinueWith(t =>Console.WriteLine("The maximum is: " + t.Result),
                              TaskContinuationOptions.ExecuteSynchronously);
            });

        // When the children are done, show any unhandled exceptions too
        parent.ContinueWith(p => {
                // I put all this text in a StringBuilder and call Console.WriteLine just once
                // because this task could execute concurrently with the task above & I don't
                // want the tasks' output interspersed
                StringBuilder sb = new StringBuilder(
                    "The following exception(s) occurred:" + Environment.NewLine);

                foreach (var e in p.Exception.Flatten().InnerExceptions)
                    sb.AppendLine("   "+ e.GetType().ToString());
                Console.WriteLine(sb.ToString());
            }, TaskContinuationOptions.OnlyOnFaulted);

        // Start the parent Task so it can start its children
        parent.Start();
        Thread.Sleep(1000);
    }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:46,代码来源:TaskFactory.cs

示例4: Run3

 public static void Run3()
 {
     CancellationTokenSource cts = new CancellationTokenSource();
     //等待按下任意一个键取消任务
     TaskFactory taskFactory = new TaskFactory();
     Task[] tasks = new Task[]
         {
             taskFactory.StartNew(() => Add(cts.Token)),
             taskFactory.StartNew(() => Add(cts.Token)),
             taskFactory.StartNew(() => Add(cts.Token))
         };
     //CancellationToken.None指示TasksEnded不能被取消
     taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None);
     Console.ReadKey();
     cts.Cancel();
     Console.ReadKey();
 }
开发者ID:yinqingzhun,项目名称:consoleApp,代码行数:17,代码来源:TaskDemo.cs

示例5: RunFactory

        public static void RunFactory()
        {
            var parent = new Task(() =>
            {
                var cts = new CancellationTokenSource();
                var tf = new TaskFactory<Int32>(cts.Token, TaskCreationOptions.AttachedToParent,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

                var childTasks = new[]
                {
                    tf.StartNew(() => Sum(cts.Token, 10000)),
                    tf.StartNew(()=>Sum(cts.Token, 20000)),
                    tf.StartNew(()=>Sum(cts.Token, Int32.MaxValue))
                };

                for (var task = 0; task < childTasks.Length; task++)
                {
                    childTasks[task].ContinueWith(t => cts.Cancel(), 
                        TaskContinuationOptions.OnlyOnFaulted);
                }

                tf.ContinueWhenAll(childTasks,
                    completedTasks =>
                        completedTasks.Where(t => 
                        t.Status == TaskStatus.RanToCompletion).Max(t => t.Result), CancellationToken.None).ContinueWith(
                    t=>Console.WriteLine("The maximum is: " + t.Result), TaskContinuationOptions.ExecuteSynchronously);

            });

            parent.ContinueWith(p =>
            {
                var sb = new StringBuilder("The following exception(s) occurred: " + Environment.NewLine);

                foreach(var e in p.Exception.Flatten().InnerExceptions)
                {
                    sb.AppendLine("    " + e.GetType());
                }
                Console.WriteLine(sb);

            }, TaskContinuationOptions.OnlyOnFaulted);

            parent.Start();
        }
开发者ID:stoneflyop1,项目名称:ThreadTestSamples,代码行数:43,代码来源:TestTask.cs

示例6: Test

        public override void Test()
        {
            var taskF = new TaskFactory();
            Console.WriteLine("SingletonOne");
            List<Task> listTask= new List<Task>();
            for (int i = 0; i < 10; i++)
                listTask.Add(taskF.StartNew(() => SingletonOne.CreateInstance().Show()));

            Task.WaitAll(listTask.ToArray());

            Console.WriteLine("SingletonTwo");
            for (int i = 0; i < 10; i++)
                listTask.Add(taskF.StartNew(() => SingletonTwo.CreateInstance().Show()));

            taskF.ContinueWhenAll(listTask.ToArray(), (a) => { Console.WriteLine(a); MessageBox.Show(a.Count().ToString()); });

            Console.WriteLine("SingletonThree");
            for (int i = 0; i < 10; i++)
                listTask.Add(taskF.StartNew(() => SingletonThree.CreateInstance().Show()));
        }
开发者ID:s455016457,项目名称:study,代码行数:20,代码来源:TestSingleon.cs

示例7: MyMain6

        public static void MyMain6()
        {
            Task parent = new Task(() =>
            {
                var cts = new CancellationTokenSource();
                var tf = new TaskFactory<Int32>(cts.Token, TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

                // Задание создает и запускает 3 дочерних задания
                var childTasks = new[]
                {
                    tf.StartNew(() => Sum6(cts.Token, 10000)),
                    tf.StartNew(() => Sum6(cts.Token, 20000)),
                    tf.StartNew(() => Sum6(cts.Token, Int32.MaxValue)) // Исключение OverflowException
                };

                // Если дочернее задание становится источником исключения,
                // отменяем все дочерние задания
                for (Int32 task = 0; task < childTasks.Length; task++)
                {
                    childTasks[task].ContinueWith(t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);
                }

                // После завершения дочерних заданий получаем максимальное
                // возвращенное значение и передаем его другому заданию
                // для вывода
                tf.ContinueWhenAll(childTasks,
                    completedTasks =>
                        completedTasks.Where(t => !t.IsFaulted && !t.IsCanceled).Max(t => t.Result),
                    CancellationToken.None)
                    .ContinueWith(t => Console.WriteLine("The maximum is: " + t.Result),
                        TaskContinuationOptions.ExecuteSynchronously);
            });

            // После завершения дочерних заданий выводим, в том числе, и необработанные исключения
            parent.ContinueWith(p =>
            {
                // Текст помещен в StringBuilder и однократно вызван
                // метод Console.WriteLine просто потому, что это задание
                // может выполняться параллельно с предыдущим,
                // и я не хочу путаницы в выводимом результате
                var sb = new StringBuilder("The following exception(s) occurred:" + Environment.NewLine);
                foreach (var e in p.Exception.Flatten().InnerExceptions)
                {
                    sb.AppendLine(" " + e.GetType().ToString());
                }

                Console.WriteLine(sb.ToString());
            }, TaskContinuationOptions.OnlyOnFaulted);

            // Запуск родительского задания, которое может запускать дочерние
            parent.Start();

            Console.ReadKey();
        }
开发者ID:alex2015,项目名称:ConsoleApplication,代码行数:54,代码来源:MyTask.cs

示例8: T04

        //You might want to create tasks with similar configuration
        public void T04()
        {
            Task parent = new Task(() => {
                var cts = new CancellationTokenSource();
                TaskFactory<int> tf = new TaskFactory<int>(
                                            cts.Token
                                            , TaskCreationOptions.AttachedToParent
                                            , TaskContinuationOptions.ExecuteSynchronously
                                            , TaskScheduler.Default);

                Task<int>[] childtasks = new Task<int>[] {
                    tf.StartNew(()=> { return 5; })
                    ,tf.StartNew(()=> { return 6; })
                    ,tf.StartNew(()=> { return 7; })

                };

                tf.ContinueWhenAll(childtasks, ct => ct.Where(t => t.Status == TaskStatus.RanToCompletion).Max(t => t.Result))
                .ContinueWith(t => Console.WriteLine("Max val is " + t.Result), TaskContinuationOptions.ExecuteSynchronously);

            });
        }
开发者ID:alandias01,项目名称:Console_practice,代码行数:23,代码来源:Tasks01.cs

示例9: StartAll

        private void StartAll(object sender, DoWorkEventArgs args)
        {
            var finished = false;
            var tasks = new List<Task>();
            var factory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
            tasks.Add(factory.StartNew(UpdateArtistInfo));
            tasks.Add(factory.StartNew(UpdateUserPlays));
            tasks.Add(factory.StartNew(UpdateArtistImages));
            tasks.Add(factory.StartNew(UpdateAlbumArt));

            factory.ContinueWhenAll(tasks.ToArray(), delegate(Task[] t) { finished = true; });

            while (!finished)
            {
                Thread.Sleep(2000);
            }
        }
开发者ID:andrewburgess,项目名称:siren,代码行数:17,代码来源:LastFMUpdater.cs

示例10: StartJudging

 /// <summary>
 /// Start Judging with given compiler
 /// </summary>
 /// <param name="Compiler">Compiler used to compile the code</param>
 public void StartJudging(Compiler Compiler, bool WaitForExit)
 {
     var programFilename = CompileCode(Compiler);
     //no compiled file means compile failed
     if (!File.Exists(programFilename))
     {
         //compilation finished
         OnCompiled?.Invoke(this, new CompilationFinishedEventArgs() { IsCompilationSucceeded = false });
         Results = new List<JudgeResult>(new JudgeResult[] { new JudgeResult() { Result = JudgeResultEnum.CompileError } });
         return;
     }
     else
     {
         OnCompiled?.Invoke(this, new CompilationFinishedEventArgs() { IsCompilationSucceeded = true });
     }
     //run if compilation successful
     //initialize taskfactory
     judgingTasks = new TaskFactory();
     cts = new CancellationTokenSource();
     Task[] tasks = new Task[Data.Datas.Count];
     //run each sample data
     Data.Datas.ForEach(d =>
     {
         tasks[Data.Datas.IndexOf(d)] = (judgingTasks.StartNew(() =>
           {
               TestProgram(programFilename, d, WaitForExit);
           }, cts.Token).ContinueWith((r) =>
           {
               OnJudged?.Invoke(this, new JudgementFinishedEventArgs() { Index = Data.Datas.IndexOf(d) });
           }));
     });
     //binding event notification
     judgingTasks.ContinueWhenAll(tasks, (t) =>
     {
         File.Delete(programFilename);
         OnJudgedAll?.Invoke();
     });
 }
开发者ID:SamLangTen,项目名称:SamsOfflineCodeJudge,代码行数:42,代码来源:Judger.cs

示例11: TestTaskFactory

        public static void TestTaskFactory()
        {
            Task parent = new Task(() =>
                {
                    var cts = new CancellationTokenSource();
                    var tf = new TaskFactory<Int32>(cts.Token,
                                                    TaskCreationOptions.AttachedToParent, //The parent task will fault only if it is attached to the children
                                                    //TaskCreationOptions.None,
                                                    TaskContinuationOptions.ExecuteSynchronously,
                                                    TaskScheduler.Default);
                    // This tasks creates and starts 3 child tasks
                    var childTasks = new[]
                        {
                            tf.StartNew(() => Sum(cts.Token, 10000)),
                            tf.StartNew(() => Sum(cts.Token, 20000)),
                            //tf.StartNew(() => Sum(cts.Token, Int32.MaxValue)) // Too big, throws OverflowException
                            tf.StartNew(() => Sum(cts.Token, 3000))
                        };

                    // If any of the child tasks throw, cancel the rest of them
                    for (Int32 task = 0; task < childTasks.Length; task++)
                        childTasks[task].ContinueWith(
                            t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

                    //Hariom - instead of cancelling try to log the error
                    for (Int32 task = 0; task < childTasks.Length; task++)
                        childTasks[task].ContinueWith(
                            t => HandleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

                    // When all children are done, get the maximum value returned from the
                    // non-faulting/canceled tasks. Then pass the maximum value to another
                    // task which displays the maximum result
                    tf.ContinueWhenAll(
                        childTasks,
                        completedTasks => completedTasks.Where(
                            t => !t.IsFaulted && !t.IsCanceled).Max(t => t.Result),
                        CancellationToken.None)
                      .ContinueWith(t => Console.WriteLine("The maximum is: " + t.Result),
                                    TaskContinuationOptions.ExecuteSynchronously);

                    //After waiting for 5 seconds cancel all the tasks and check if the operation cancelled exception is thrown
                    //Thread.Sleep(5000);
                    cts.Cancel();
                });
            // When the children are done, show any unhandled exceptions too
            parent.ContinueWith(p =>
                {
                    //NOTE: For some reason the exception thrown by ct.ThrowIfCancellationRequested() is not making this
                    //delegate to execute, but it executes for other exceptions like Overflow or If I throw my own exception

                    // I put all this text in a StringBuilder and call Console.WriteLine just once
                    // because this task could execute concurrently with the task above & I don't
                    // want the tasks' output interspersed
                    StringBuilder sb = new StringBuilder(
                        "The following exception(s) occurred:" + Environment.NewLine);
                    foreach (var e in p.Exception.Flatten().InnerExceptions)
                        sb.AppendLine(" " + e.GetType().ToString());
                    Console.WriteLine(sb.ToString());
                }, TaskContinuationOptions.OnlyOnFaulted);
            // Start the parent Task so it can start its children
            parent.Start();
        }
开发者ID:hkuntal,项目名称:TeamWorkManagement,代码行数:62,代码来源:ThreadingTest.cs

示例12: TaskTest3

        /// <summary>
        /// 任务工厂
        /// </summary>
        public static void TaskTest3()
        {
            Task parent = new Task(() =>
            {
                var cts = new CancellationTokenSource();
                var tf = new TaskFactory<int>(cts.Token, TaskCreationOptions.AttachedToParent,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                
                //这个任务创建并启动三个子任务
                var childTasks = new[] { 
                    tf.StartNew(()=>Sum(cts.Token, 10000)),
                    tf.StartNew(()=>Sum(cts.Token, 10000)),
                    tf.StartNew(()=>Sum(cts.Token, int.MaxValue))
                };

                //任何子任务抛出异常,就取消子任务
                for (int task = 0; task < childTasks.Length; task++)
                {
                    childTasks[task].ContinueWith(t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);
                }

                //所有子任务完成以后,从未出错/未取消的的任务获取返回的最大值
                //然后将最大值传给另一个任务来显示最大结果
                tf.ContinueWhenAll(childTasks, completedTasks => completedTasks.Where(t=>!t.IsFaulted && !t.IsCanceled).Max(t=>t.Result), 
                    CancellationToken.None).ContinueWith(t=>Console.WriteLine("The maximum is: " + t.Result),
                    TaskContinuationOptions.ExecuteSynchronously);
            });

            parent.ContinueWith(p => {
                StringBuilder sb = new StringBuilder("The following exception(s) occurred: " + Environment.NewLine);
                foreach (var e in p.Exception.Flatten().InnerExceptions)
                {
                    sb.AppendLine(" " + e.GetType().ToString());
                    Console.WriteLine(sb.ToString());
                }
            }, TaskContinuationOptions.OnlyOnFaulted);

            parent.Start();
        }
开发者ID:twfx7758,项目名称:LearnDemo,代码行数:42,代码来源:LearnThread.cs


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