C#学习 - 关于Task的几种用法

1. 使用Task Factory创建

           var tf = new TaskFactory();
           var t1 = tf.StartNew(TaskMethod, "using a task factory");
 

2. 使用new Task()

            var t3 = new Task(TaskMethod, "using task constructor and start");
            t3.Start();

3. 使用task.Run( )

            var t4 = Task.Run(() => TaskMethod("using the run method"));


4. 同步启动一个Task

            var t1 = new Task(TaskMethod, "run sync");
            t1.RunSynchronously();


5. 使用带返回参数的泛型定义 Task(Funcf, object state)

        static Tuple TaskMethodWithResult(object division)
        {
            Tuple input = (Tuple)division;
            int result = input.First / input.Second;
            int remainder = input.First % input.Second;
            return new Tuple(result, remainder);
        }

        static void TaskWithResult()
        {
            var t1 = new Task>(TaskMethodWithResult, new Tuple(8, 3));
            t1.Start();
            Console.WriteLine(t1.Result);
            t1.Wait();
            Console.WriteLine("result from task: {0} {1}", t1.Result.First, t1.Result.Second);
        }

6. 使用ContinueWith()在一个任务结束后,创建一个新的Task

        static void FirstToDo()
        {
            Console.WriteLine("First Job to do.");
        }

        static void SecondToDo(Task t)
        {
            Console.WriteLine("task {0} finished, new task is {1}", t.Id, Task.CurrentId);
            Console.WriteLine("Second Job to do.");
        }

        static void TaskContinueWith()
        {
            var t1 = new Task(FirstToDo);
            var t2 = t1.ContinueWith(SecondToDo);
            t1.Start();
        }



你可能感兴趣的:(C#)