zoukankan      html  css  js  c++  java
  • 启动新任务和子任务

     1         private static void StartNewTask()
     2         {
     3             //创建并启动一个Task
     4             Task<string> task = Task.Run(() => TaskTest("TaskTest1"));
     5 
     6             //继续另一个任务
     7             //ContinueWith返回一个新的Task引用
     8             Task cwt = task.ContinueWith(t => Console.WriteLine(t.Result));
     9             //继续另一个任务
    10             task.ContinueWith(t => Console.WriteLine("Complete"));
    11         }
    12 
    13         private static void StartChildTask()
    14         {
    15             //返回类型为string[]的Task
    16             Task<string[]> parent = new Task<string[]>(() =>
    17             {
    18                 //创建一个数组来存储结果
    19                 string[] result = new string[3];
    20 
    21                 //创建并启动3个子任务
    22                 //指定将任务附加到任务层次结构中的某个父级
    23                 new Task(() => result[0] = TaskTest("TaskTest0"), TaskCreationOptions.AttachedToParent).Start();
    24                 new Task(() => result[1] = TaskTest("TaskTest1"), TaskCreationOptions.AttachedToParent).Start();
    25                 new Task(() => result[2] = TaskTest("TaskTest2"), TaskCreationOptions.AttachedToParent).Start();
    26 
    27                 //返回对数组的引用,即使数组元素可能还没有初始化
    28                 return result;
    29             });
    30 
    31             //父任务及其子任务完成后,用一个延续任务显示结果
    32             var cwt = parent.ContinueWith((parentTask) => Array.ForEach(parentTask.Result, Console.WriteLine));
    33 
    34             //启动父任务,以便于启动其子任务
    35             parent.Start();
    36         }
    37 
    38         private static string TaskTest(string str)
    39         {
    40             Console.WriteLine("TaskTest_" + str);
    41             return str;
    42         }
  • 相关阅读:
    js计算两个时间相差天数
    享元模式
    外观模式
    组合模式
    装饰者模式
    桥接模式
    适配器模式
    元素量词 ? + *
    linux安装使用7zip
    linux shell使用别名,切换当前目录
  • 原文地址:https://www.cnblogs.com/xuejietong/p/8901844.html
Copyright © 2011-2022 走看看