C# Task详解

摘要:
1.任务线程池的优点与线程相比有很多优点,但线程池不方便使用。例如:◆ ThreadPool不支持线程取消、完成和失败通知等交互操作;◆ ThreadPool不支持线程执行顺序;在过去,如果开发人员想要实现上述功能,他们需要完成大量额外的工作。现在,FCL提供了一个更强大的概念:任务。任务基于线程池执行

1、Task的优势

  ThreadPool相比Thread来说具备了很多优势,但是ThreadPool却又存在一些使用上的不方便。比如:
  ◆ ThreadPool不支持线程的取消、完成、失败通知等交互性操作;
  ◆ ThreadPool不支持线程执行的先后次序;
  以往,如果开发者要实现上述功能,需要完成很多额外的工作,现在,FCL中提供了一个功能更强大的概念:Task。Task在线程池的基础上进行了优化,并提供了更多的API。在FCL4.0中,如果我们要编写多线程程序,Task显然已经优于传统的方式。
  以下是一个简单的任务示例:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task t = new Task(() =>
            {
                Console.WriteLine("任务开始工作……");
                //模拟工作过程
                Thread.Sleep(5000);
            });
            t.Start();
            t.ContinueWith((task) =>
            {
                Console.WriteLine("任务完成,完成时候的状态为:");
                Console.WriteLine("IsCanceled={0}	IsCompleted={1}	IsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
            });
            Console.ReadKey();
        }
    }
}

2、Task的用法

  2.1、创建任务

  (一)无返回值的方式
  方式1:

  var t1 = new Task(() => TaskMethod("Task 1"));
  t1.Start();
  Task.WaitAll(t1);//等待所有任务结束 
  注:任务的状态:
  Start之前为:Created
  Start之后为:WaitingToRun 

方式2:

 Task.Run(() => TaskMethod("Task 2"));

 方式3:

  Task.Factory.StartNew(() => TaskMethod("Task 3")); 直接异步的方法 
  //或者
  var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
  Task.WaitAll(t3);//等待所有任务结束
  //任务的状态:
  Start之前为:Running
  Start之后为:Running
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var t1 = new Task(() => TaskMethod("Task 1"));
            var t2 = new Task(() => TaskMethod("Task 2"));
            t2.Start();
            t1.Start();
            Task.WaitAll(t1, t2);
            Task.Run(() => TaskMethod("Task 3"));
            Task.Factory.StartNew(() => TaskMethod("Task 4"));
            //标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。
            Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);

            #region 常规的使用方式
            Console.WriteLine("主线程执行业务处理.");
            //创建任务
            Task task = new Task(() =>
            {
                Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                }
            });
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            task.Start();
            Console.WriteLine("主线程执行其他处理");
            task.Wait();
            #endregion

            Thread.Sleep(TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }

        static void TaskMethod(string name)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
        }
    }
}
复制代码
  async/await的实现方式:


复制代码
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        async static void AsyncFunction()
        {
            await Task.Delay(1);
            Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(string.Format("AsyncFunction:i={0}", i));
            }
        }

        public static void Main()
        {
            Console.WriteLine("主线程执行业务处理.");
            AsyncFunction();
            Console.WriteLine("主线程执行其他处理");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(string.Format("Main:i={0}", i));
            }
            Console.ReadLine();
        }
    }
}

 (二)带返回值的方式
  方式4:

 Task<int> task = CreateTask("Task 1");
  task.Start(); 
  int result = task.Result;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static Task<int> CreateTask(string name)
        {
            return new Task<int>(() => TaskMethod(name));
        }

        static void Main(string[] args)
        {
            TaskMethod("Main Thread Task");
            Task<int> task = CreateTask("Task 1");
            task.Start();
            int result = task.Result;
            Console.WriteLine("Task 1 Result is: {0}", result);

            task = CreateTask("Task 2");
            //该任务会运行在主线程中
            task.RunSynchronously();
            result = task.Result;
            Console.WriteLine("Task 2 Result is: {0}", result);

            task = CreateTask("Task 3");
            Console.WriteLine(task.Status);
            task.Start();

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }

            Console.WriteLine(task.Status);
            result = task.Result;
            Console.WriteLine("Task 3 Result is: {0}", result);

            #region 常规使用方式
            //创建任务
            Task<int> getsumtask = new Task<int>(() => Getsum());
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            getsumtask.Start();
            Console.WriteLine("主线程执行其他处理");
            //等待任务的完成执行过程。
            getsumtask.Wait();
            //获得任务的执行结果
            Console.WriteLine("任务执行结果:{0}", getsumtask.Result.ToString());
            #endregion
        }

        static int TaskMethod(string name)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            return 42;
        }

        static int Getsum()
        {
            int sum = 0;
            Console.WriteLine("使用Task执行异步操作.");
            for (int i = 0; i < 100; i++)
            {
                sum += i;
            }
            return sum;
        }
    }
}
  async/await的实现:
using
System; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { public static void Main() { var ret1 = AsyncGetsum(); Console.WriteLine("主线程执行其他处理"); for (int i = 1; i <= 3; i++) Console.WriteLine("Call Main()"); int result = ret1.Result; //阻塞主线程 Console.WriteLine("任务执行结果:{0}", result); } async static Task<int> AsyncGetsum() { await Task.Delay(1); int sum = 0; Console.WriteLine("使用Task执行异步操作."); for (int i = 0; i < 100; i++) { sum += i; } return sum; } } }

 2.2、组合任务.ContinueWith

   简单Demo:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            //创建一个任务
            Task<int> task = new Task<int>(() =>
            {
                int sum = 0;
                Console.WriteLine("使用Task执行异步操作.");
                for (int i = 0; i < 100; i++)
                {
                    sum += i;
                }
                return sum;
            });
            //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
            task.Start();
            Console.WriteLine("主线程执行其他处理");
            //任务完成时执行处理。
            Task cwt = task.ContinueWith(t =>
            {
                Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());
            });
            task.Wait();
            cwt.Wait();
        }
    }
}

 任务的串行:

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcurrentStack<int> stack = new ConcurrentStack<int>();

            //t1先串行
            var t1 = Task.Factory.StartNew(() =>
            {
                stack.Push(1);
                stack.Push(2);
            });

            //t2,t3并行执行
            var t2 = t1.ContinueWith(t =>
            {
                int result;
                stack.TryPop(out result);
                Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //t2,t3并行执行
            var t3 = t1.ContinueWith(t =>
            {
                int result;
                stack.TryPop(out result);
                Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //等待t2和t3执行完
            Task.WaitAll(t2, t3);

            //t7串行执行
            var t4 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("当前集合元素个数:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
            });
            t4.Wait();
        }
    }
}

子任务:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            Task<string[]> parent = new Task<string[]>(state =>
            {
                Console.WriteLine(state);
                string[] result = new string[2];
                //创建并启动子任务
                new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();
                new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();
                return result;
            }, "我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。");
            //任务处理完成后执行的操作
            parent.ContinueWith(t =>
            {
                Array.ForEach(t.Result, r => Console.WriteLine(r));
            });
            //启动父任务
            parent.Start();
            //等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束
            //parent.Wait();
            Console.ReadLine();

        }
    }
}

动态并行(TaskCreationOptions.AttachedToParent) 父任务等待所有子任务完成后 整个任务才算完成

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Node
    {
        public Node Left { get; set; }
        public Node Right { get; set; }
        public string Text { get; set; }
    }


    class Program
    {
        static Node GetNode()
        {
            Node root = new Node
            {
                Left = new Node
                {
                    Left = new Node
                    {
                        Text = "L-L"
                    },
                    Right = new Node
                    {
                        Text = "L-R"
                    },
                    Text = "L"
                },
                Right = new Node
                {
                    Left = new Node
                    {
                        Text = "R-L"
                    },
                    Right = new Node
                    {
                        Text = "R-R"
                    },
                    Text = "R"
                },
                Text = "Root"
            };
            return root;
        }

        static void Main(string[] args)
        {
            Node root = GetNode();
            DisplayTree(root);
        }

        static void DisplayTree(Node root)
        {
            var task = Task.Factory.StartNew(() => DisplayNode(root),
                                            CancellationToken.None,
                                            TaskCreationOptions.None,
                                            TaskScheduler.Default);
            task.Wait();
        }

        static void DisplayNode(Node current)
        {

            if (current.Left != null)
                Task.Factory.StartNew(() => DisplayNode(current.Left),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            if (current.Right != null)
                Task.Factory.StartNew(() => DisplayNode(current.Right),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            Console.WriteLine("当前节点的值为{0};处理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
        }
    }
}

2.3、取消任务 CancellationTokenSource

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static int TaskMethod(string name, int seconds, CancellationToken token)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            for (int i = 0; i < seconds; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                if (token.IsCancellationRequested) return -1;
            }
            return 42 * seconds;
        }

        private static void Main(string[] args)
        {
            var cts = new CancellationTokenSource();
            var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
            Console.WriteLine(longTask.Status);
            cts.Cancel();
            Console.WriteLine(longTask.Status);
            Console.WriteLine("First task has been cancelled before execution");
            cts = new CancellationTokenSource();
            longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
            longTask.Start();
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine(longTask.Status);
            }
            cts.Cancel();
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine(longTask.Status);
            }

            Console.WriteLine("A task has been completed with result {0}.", longTask.Result);
        }
    }
}

2.4、处理任务中的异常

  单个任务:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            throw new Exception("Boom!");
            return 42 * seconds;
        }

        static void Main(string[] args)
        {
            try
            {
                Task<int> task = Task.Run(() => TaskMethod("Task 2", 2));
                int result = task.GetAwaiter().GetResult();
                Console.WriteLine("Result: {0}", result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);
            }
            Console.WriteLine("----------------------------------------------");
            Console.WriteLine();
        }
    }
}

多个任务:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            throw new Exception(string.Format("Task {0} Boom!", name));
            return 42 * seconds;
        }


        public static void Main(string[] args)
        {
            try
            {
                var t1 = new Task<int>(() => TaskMethod("Task 3", 3));
                var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
                var complexTask = Task.WhenAll(t1, t2);
                var exceptionHandler = complexTask.ContinueWith(t =>
                        Console.WriteLine("Result: {0}", t.Result),
                        TaskContinuationOptions.OnlyOnFaulted
                    );
                t1.Start();
                t2.Start();
                Task.WaitAll(t1, t2);
            }
            catch (AggregateException ex)
            {
                ex.Handle(exception =>
                {
                    Console.WriteLine(exception.Message);
                    return true;
                });
            }
        }
    }
}

    async/await的方式:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task ThrowNotImplementedExceptionAsync()
        {
            throw new NotImplementedException();
        }

        static async Task ThrowInvalidOperationExceptionAsync()
        {
            throw new InvalidOperationException();
        }

        static async Task Normal()
        {
            await Fun();
        }

        static Task Fun()
        {
            return Task.Run(() =>
            {
                for (int i = 1; i <= 10; i++)
                {
                    Console.WriteLine("i={0}", i);
                    Thread.Sleep(200);
                }
            });
        }

        static async Task ObserveOneExceptionAsync()
        {
            var task1 = ThrowNotImplementedExceptionAsync();
            var task2 = ThrowInvalidOperationExceptionAsync();
            var task3 = Normal();


            try
            {
                //异步的方式
                Task allTasks = Task.WhenAll(task1, task2, task3);
                await allTasks;
                //同步的方式
                //Task.WaitAll(task1, task2, task3);
            }
            catch (NotImplementedException ex)
            {
                Console.WriteLine("task1 任务报错!");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("task2 任务报错!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("任务报错!");
            }

        }

        public static void Main()
        {
            Task task = ObserveOneExceptionAsync();
            Console.WriteLine("主线程继续运行........");
            task.Wait();
        }
    }
}

2.5、Task.FromResult的应用

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static IDictionary<string, string> cache = new Dictionary<string, string>()
        {
            {"0001","A"},
            {"0002","B"},
            {"0003","C"},
            {"0004","D"},
            {"0005","E"},
            {"0006","F"},
        };

        public static void Main()
        {
            Task<string> task = GetValueFromCache("0006");
            Console.WriteLine("主程序继续执行。。。。");
            string result = task.Result;
            Console.WriteLine("result={0}", result);

        }

        private static Task<string> GetValueFromCache(string key)
        {
            Console.WriteLine("GetValueFromCache开始执行。。。。");
            string result = string.Empty;
            //Task.Delay(5000);
            Thread.Sleep(5000);
            Console.WriteLine("GetValueFromCache继续执行。。。。");
            if (cache.TryGetValue(key, out result))
            {
                return Task.FromResult(result);
            }
            return Task.FromResult("");
        }

    }
}

 2.6、使用IProgress实现异步编程的进程通知

  IProgress<in T>只提供了一个方法void Report(T value),通过Report方法把一个T类型的值报告给IProgress,然后IProgress<in T>的实现类Progress<in T>的构造函数接收类型为Action<T>的形参,通过这个委托让进度显示在UI界面中。

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void DoProcessing(IProgress<int> progress)
        {
            for (int i = 0; i <= 100; ++i)
            {
                Thread.Sleep(100);
                if (progress != null)
                {
                    progress.Report(i);
                }
            }
        }

        static async Task Display()
        {
            //当前线程
            var progress = new Progress<int>(percent =>
            {
                Console.Clear();
                Console.Write("{0}%", percent);
            });
            //线程池线程
            await Task.Run(() => DoProcessing(progress));
            Console.WriteLine("");
            Console.WriteLine("结束");
        }

        public static void Main()
        {
            Task task = Display();
            task.Wait();
        }
    }
}

 2.7、Factory.FromAsync的应用 (简APM模式(委托)转换为任务)(BeginXXX和EndXXX)

  带回调方式的

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private delegate string AsynchronousTask(string threadName);

        private static string Test(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
        }

        private static void Callback(IAsyncResult ar)
        {
            Console.WriteLine("Starting a callback...");
            Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
        }

        //执行的流程是 先执行Test--->Callback--->task.ContinueWith
        static void Main(string[] args)
        {
            AsynchronousTask d = Test;
            Console.WriteLine("Option 1");
            Task<string> task = Task<string>.Factory.FromAsync(
                d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}",
                t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);

        }
    }
}

不带回调方式的

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private delegate string AsynchronousTask(string threadName);

        private static string Test(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
        }

        //执行的流程是 先执行Test--->task.ContinueWith
        static void Main(string[] args)
        {
            AsynchronousTask d = Test;
            Task<string> task = Task<string>.Factory.FromAsync(
                d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");
            task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
                t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);

        }
    }
}

参考2

简介:

Task 对象是一种的中心思想基于任务的异步模式首次引入.NET Framework 4 中。 因为由执行工作Task对象通常以异步方式执行线程池线程上而不是以同步方式在主应用程序线程中,可以使用Status属性,并将IsCanceled, IsCompleted,和IsFaulted属性,以确定任务的状态。


一.Task的创建

1.创建Task类

(1)

1
2
3
4
5
Task task = new Task(() =>
{
    Console.WriteLine("hello world!");
});
task.Start(); 

(2)

1
2
3
4
new Task(() =>
{
    Console.WriteLine("hello world!");
}).Start();

(3)带参数

1
2
3
4
new Task(x =>
{
    Console.WriteLine(x.ToString());
}, "hello world!").Start();

(4)带返回值

1
2
3
4
5
6
Task<string> t = new Task<string>(x =>
{
    return x.ToString();
}, "hello world!");
t.Start();
Console.WriteLine(t.Result);

  

2.Task.Factory.StartNew

(1)

1
2
3
4
Task.Factory.StartNew(() =>
{
    Console.WriteLine("hello world!");
});

(2)带参数

1
2
3
4
Task.Factory.StartNew(x =>
{
    Console.WriteLine(x.ToString());
}, "hello world!");

  

(3)带返回值

1
2
3
4
Task<string> t = Task.Factory.StartNew<string>(() =>
{
    return "hello world!";
});<br>        Console.WriteLine(t.Result);

  

3.Task.Run

1
2
3
4
Task.Run(() =>
{
    Console.WriteLine("hello world!");
});

4.TaskStatus

1
2
3
4
5
6
7
8
Created = 0, //该任务已初始化,但尚未被计划。
WaitingForActivation = 1, //该任务正在等待 .NET Framework 基础结构在内部将其激活并进行计划。
WaitingToRun = 2,//该任务已被计划执行,但尚未开始执行。
Running = 3, //该任务正在运行,但尚未完成。
WaitingForChildrenToComplete = 4,//该任务已完成执行,正在隐式等待附加的子任务完成。
RanToCompletion = 5,//已成功完成执行的任务。
Canceled = 6, //该任务已通过对其自身的 CancellationToken 引发 OperationCanceledException 对取消进行了确认,此时该标记处于已发送信号状态;或者在该任务开始执行之前,已向该任务的CancellationToken 发出了信号。 有关详细信息,请参阅任务取消。
Faulted = 7 //由于未处理异常的原因而完成的任务。

  

回到顶部

二. TaskCreationOptions

 Task.Factory.StartNew和创建Task类可以带TaskCreationOptions参数而Task.Run不可以带

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//
// 摘要:
//     指定应使用默认行为。
None = 0,
//
// 摘要:
//     提示 System.Threading.Tasks.TaskScheduler 以一种尽可能公平的方式安排任务,这意味着较早安排的任务将更可能较早运行,而较晚安排运行的任务将更可能较晚运行。
PreferFairness = 1,
//
// 摘要:
//     指定任务将是长时间运行的、粗粒度的操作,涉及比细化的系统更少、更大的组件。 它会向 System.Threading.Tasks.TaskScheduler
//     提示,过度订阅可能是合理的。 可以通过过度订阅创建比可用硬件线程数更多的线程。 它还将提示任务计划程序:该任务需要附加线程,以使任务不阻塞本地线程池队列中其他线程或工作项的向前推动。
LongRunning = 2,
//
// 摘要:
//     指定将任务附加到任务层次结构中的某个父级。 默认情况下,子任务(即由外部任务创建的内部任务)将独立于其父任务执行。 可以使用 System.Threading.Tasks.TaskContinuationOptions.AttachedToParent
//     选项以便将父任务和子任务同步。 请注意,如果使用 System.Threading.Tasks.TaskCreationOptions.DenyChildAttach
//     选项配置父任务,则子任务中的 System.Threading.Tasks.TaskCreationOptions.AttachedToParent 选项不起作用,并且子任务将作为分离的子任务执行。
//     有关详细信息,请参阅附加和分离的子任务。
AttachedToParent = 4,
//
// 摘要:
//     指定任何尝试作为附加的子任务执行(即,使用 System.Threading.Tasks.TaskCreationOptions.AttachedToParent
//     选项创建)的子任务都无法附加到父任务,会改成作为分离的子任务执行。 有关详细信息,请参阅附加和分离的子任务。
DenyChildAttach = 8,
//
// 摘要:
//     防止环境计划程序被视为已创建任务的当前计划程序。 这意味着像 StartNew 或 ContinueWith 创建任务的执行操作将被视为 System.Threading.Tasks.TaskScheduler.Default
//     当前计划程序。
HideScheduler = 16

1. LongRunning

任务是长时间任务,就需要用LongRunning,可能会创建一个非线程池线程来执行该任务,防止阻塞线程池队列中的其他线程

1
2
3
4
5
6
7
8
9
10
11
12
private static void fun8()
{
    Task.Factory.StartNew(() =>
    {
        Console.WriteLine($"task1.线程 id {Thread.CurrentThread.ManagedThreadId}. 是否为线程池线程: {Thread.CurrentThread.IsThreadPoolThread}");
    });
 
    Task.Factory.StartNew(() =>
    {
        Console.WriteLine($"task2.线程 id {Thread.CurrentThread.ManagedThreadId}. 是否为线程池线程: {Thread.CurrentThread.IsThreadPoolThread}");
    }, TaskCreationOptions.LongRunning);
}

 运行结果:

C# Task详解第1张

 2. 父子任务(AttachedToParent,DenyChildAttach)

AttachedToParent:将子任务附加到父任务上,表现为:附加到父任务上的所有子任务都结束,父任务才结束

DenyChildAttach:不允许子任务附加到父任务上

(1)子任务不附加到父任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static void fun5()
{
    Task t = Task.Factory.StartNew(() =>
    {
        Console.WriteLine("parent");
 
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("child");
        });
    });
    t.ContinueWith(x =>
    {
        Console.WriteLine("parent over");
    });
}

 运行结果:

C# Task详解第2张

(2)子任务附加到父任务上,使用AttachedToParent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static void fun6()
{
    Task t = Task.Factory.StartNew(() =>
    {
        Console.WriteLine("parent");
 
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("child");
        },TaskCreationOptions.AttachedToParent);
    });
    t.ContinueWith(x =>
    {
        Console.WriteLine("parent over");
    });
}

 运行结果:

C# Task详解第3张

(3)拒绝子任务附加到父任务上,使用DenyChildAttach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static void fun7()
{
    Task t = Task.Factory.StartNew(() =>
    {
        Console.WriteLine("parent");
 
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("child");
        }, TaskCreationOptions.AttachedToParent);
    }, TaskCreationOptions.DenyChildAttach);
    t.ContinueWith(x =>
    {
        Console.WriteLine("parent over");
    });
}

  运行结果:

C# Task详解第4张

回到顶部

 三.CancellationToken 取消任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private static void fun4()
{
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    CancellationToken Token = cancellationTokenSource.Token;
    //结束任务回调
    Token.Register(() =>
    {
        Console.WriteLine("canceled");
    });
 
    Task.Factory.StartNew(() =>
    {
        try
        {
            while (true)
            {
                Console.WriteLine("hello world!");
                Thread.Sleep(100);
                Token.ThrowIfCancellationRequested();
            }
        }
        catch (OperationCanceledException ocex)
        {
        }
        catch (ObjectDisposedException odex)
        {
        }
        catch (Exception ex)
        {
        }
 
    }, Token);
 
    Thread.Sleep(1000);
 
    cancellationTokenSource.Cancel();
}

 

执行结果:

C# Task详解第5张

当执行cancellationTokenSource.Cancel()后,任务进行到Token.ThrowIfCancellationRequested()代码后,throw出OperationCanceledException异常,才结束任务并执行cancel回调


 四.方法

Wait等待 System.Threading.Tasks.Task 完成执行过程
WaitAll 等待提供的所有 System.Threading.Tasks.Task 对象完成执行过程
WaitAny 等待提供的任一 System.Threading.Tasks.Task 对象完成执行过程
WhenAll 创建一个任务,该任务将在所有 System.Threading.Tasks.Task 对象都完成时完成
WhenAny 任何提供的任务已完成时,创建将完成的任务
ContinueWith 创建一个在目标 System.Threading.Tasks.Task 完成时异步执行的延续任务

1 Wait

阻塞当前线程,等待任务执行完成

1
2
3
4
5
6
7
8
9
10
//等待 System.Threading.Tasks.Task 在指定的毫秒数内完成执行。
public bool Wait(int millisecondsTimeout);
//等待 System.Threading.Tasks.Task 完成执行过程。 如果在任务完成之前取消标记已取消,等待将终止。
public void Wait(CancellationToken cancellationToken);
//等待 System.Threading.Tasks.Task 完成执行过程。 如果在任务完成之前超时间隔结束或取消标记已取消,等待将终止。      
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken);      
//等待 System.Threading.Tasks.Task 完成执行过程。
public void Wait();
//等待 System.Threading.Tasks.Task 在指定的时间间隔内完成执行。
public bool Wait(TimeSpan timeout);

使用方式:

1
2
3
t.Wait();//无限等待
t.Wait(100);//等待100ms
t.Wait(TimeSpan.FromMilliseconds(1500));//等待1500ms

例:

1
2
3
4
5
6
7
8
9
10
private static void fun9()
{
    Task t = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("task");
    });
    t.Wait();
    Console.WriteLine("main");
}

 运行结果:

C# Task详解第6张

2.WaitAll 

阻塞当前线程,等待所有任务执行完成

1
2
3
4
5
6
7
8
9
10
//等待提供的所有 System.Threading.Tasks.Task 对象完成执行过程。
public static void WaitAll(params Task[] tasks);
//等待所有提供的可取消 System.Threading.Tasks.Task 对象在指定的时间间隔内完成执行。
public static bool WaitAll(Task[] tasks, TimeSpan timeout);
//等待所有提供的 System.Threading.Tasks.Task 在指定的毫秒数内完成执行。
public static bool WaitAll(Task[] tasks, int millisecondsTimeout);
//等待提供的所有 System.Threading.Tasks.Task 对象完成执行过程(除非取消等待)。
public static void WaitAll(Task[] tasks, CancellationToken cancellationToken);
//等待提供的所有 System.Threading.Tasks.Task 对象在指定的毫秒数内完成执行,或等到取消等待。
public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken);

  使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private static void fun10()
{
    Task t1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("task1");
    });
 
    Task t2 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(150);
        Console.WriteLine("task2");
    });
 
    //Task.WaitAll(t1, t2);
    //Task.WaitAll(new Task[] { t1, t2 }, 200);
    Task.WaitAll(new Task[] { t1, t2 }, TimeSpan.FromMilliseconds(200));
    Console.WriteLine("main");
}

  

 运行结果:

C# Task详解第7张

3.WaitAny

阻塞当前线程,等待任一任务执行完成

1
2
3
4
5
6
7
8
9
10
//等待提供的任一 System.Threading.Tasks.Task 对象完成执行过程。
public static int WaitAny(params Task[] tasks);
//等待任何提供的 System.Threading.Tasks.Task 对象在指定的时间间隔内完成执行。
public static int WaitAny(Task[] tasks, TimeSpan timeout);
//等待任何提供的 System.Threading.Tasks.Task 对象在指定的毫秒数内完成执行。
public static int WaitAny(Task[] tasks, int millisecondsTimeout);
//等待提供的任何 System.Threading.Tasks.Task 对象完成执行过程(除非取消等待)。
public static int WaitAny(Task[] tasks, CancellationToken cancellationToken);
//等待提供的任何 System.Threading.Tasks.Task 对象在指定的毫秒数内完成执行,或等到取消标记取消。
public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken);

 使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private static void fun11()
{
    Task t1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("task1");
    });
 
    Task t2 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(150);
        Console.WriteLine("task2");
    });
 
    //Task.WaitAny(t1, t2);
    //Task.WaitAny(new Task[] { t1, t2 }, 200);
    Task.WaitAny(new Task[] { t1, t2 }, TimeSpan.FromMilliseconds(200));
    Console.WriteLine("main");
}

 结果:

C# Task详解第8张

4.WhenAll

不阻塞当前线程,等待所有任务执行完成后,可以进行ContinueWith

1
2
3
4
5
6
7
8
//创建一个任务,该任务将在可枚举集合中的所有 System.Threading.Tasks.Task 对象都完成时完成。
public static Task WhenAll(IEnumerable<Task> tasks);
//创建一个任务,该任务将在数组中的所有 System.Threading.Tasks.Task 对象都完成时完成。
public static Task WhenAll(params Task[] tasks);
//创建一个任务,该任务将在可枚举集合中的所有 System.Threading.Tasks.Task`1 对象都完成时完成。
public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks);
//创建一个任务,该任务将在数组中的所有 System.Threading.Tasks.Task`1 对象都完成时完成。
public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks);

  使用:

(1)不带返回值 

1
public static Task WhenAll(params Task[] tasks);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static void fun12()
{
    Task t1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("task1");
    });
 
    Task t2 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(150);
        Console.WriteLine("task2");
    });
 
    Task.WhenAll(t1, t2).ContinueWith(t =>
    {
        Console.WriteLine("WhenAll");
    });
 
    Console.WriteLine("main");
}

  执行结果:

C# Task详解第9张

(2)带返回值

1
public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private static void fun13()
{
    Task<string> t1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("task1");
        return "task1";
    });
 
    Task<string> t2 = Task.Factory.StartNew<string>(() =>
    {
        Thread.Sleep(150);
        Console.WriteLine("task2");
        return "task2";
    });
 
    Task.WhenAll(new Task<string>[] { t1, t2 }).ContinueWith(t =>
    {
        string s = "WhenAll:";
        foreach (string item in t.Result)
        {
            s += item;
        }
        Console.WriteLine(s);
    });
 
    Console.WriteLine("main");
}

  执行结果:

C# Task详解第10张

5.WhenAny

1
2
3
4
5
6
7
8
//任何提供的任务已完成时,创建将完成的任务。
public static Task<Task> WhenAny(params Task[] tasks);
//任何提供的任务已完成时,创建将完成的任务。
public static Task<Task> WhenAny(IEnumerable<Task> tasks);
//任何提供的任务已完成时,创建将完成的任务。
public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks);
//任何提供的任务已完成时,创建将完成的任务。
public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks);

 使用:

(1)不带参数

1
public static Task<Task> WhenAny(params Task[] tasks);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static void fun14()
{
    Task t1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(100);
        Console.WriteLine("task1");
    });
 
    Task t2 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(150);
        Console.WriteLine("task2");
    });
 
    Task.WhenAny(t1, t2).ContinueWith(t =>
    {
        Console.WriteLine("WhenAny1");
    });
 
    Console.WriteLine("main");
}

  运行结果:

C# Task详解第11张

(2)带参数:

1
public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private static void fun15()
        {
            Task<string> t1 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(100);
                Console.WriteLine("task1");
                return "response task1";
            });
 
            Task<string> t2 = Task.Factory.StartNew<string>(() =>
            {
                Thread.Sleep(150);
                Console.WriteLine("task2");
                return "response task2";
            });
 
            Task.WhenAny(new Task<string>[] { t1, t2 }).ContinueWith(t =>
            {
                t.Result.ContinueWith(tt =>
                {
                    Console.WriteLine(tt.Result);
                });
            });
 
            Console.WriteLine("main");
        } 

运行结果:

C# Task详解第12张

6.ContinueWith

相当于回调

6.1使用

(1)使用lambda表达式方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static void fun1()
{
    Console.WriteLine("start");
    Task<string> task1 = new Task<string>(() =>
    {
        Console.WriteLine("task0");
        return "task1";
    });
    Task<string> task2 = task1.ContinueWith(t =>
    {
        Console.WriteLine(t.Result);
        return "task2";
    });
    task1.Start();
    Console.WriteLine("end");
    Console.ReadKey();
}

2.使用函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static void fun2()
       {
           Console.WriteLine("start");
           Task<string> task1 = new Task<string>(doTask1);
           Task<string> task2 = task1.ContinueWith(doTask2);
           task1.Start();
           Console.WriteLine("end");
           Console.ReadKey();
       }
 
       private static string doTask1()
       {
           Console.WriteLine("task0");
           return "task1";
       }
 
       private static string doTask2(Task<string> t)
       {
           Console.WriteLine(t.Result);
           return "task2";
       }

  运行结果:

C# Task详解第13张

 6.2 ContineWith和task可能不在同一线程上

例:

1
2
3
4
5
6
7
8
9
10
private static void fun16()
       {
           Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"task {Thread.CurrentThread.ManagedThreadId}");
            }).ContinueWith(t =>
            {
                Console.WriteLine($"ContinueWith {Thread.CurrentThread.ManagedThreadId}");
            });
       }

  运行结果:

C# Task详解第14张

回到顶部

 七.TaskFactory类

方法:

StartNew创建并启动任务
ContinueWhenAll创建一个延续任务,该任务在一组指定的任务完成后开始
ContinueWhenAny创建一个延续 System.Threading.Tasks.Task,它将在提供的组中的任何任务完成后马上开始
FromAsync创建一个 System.Threading.Tasks.Task`1,表示符合异步编程模型模式的成对的开始和结束方法

1.ContinueWhenAll

相当于回调

效果其实和WhenAll差不多,只不过ContineWhenAll采用了回调的方式

使用:带返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static void fun17()
{
    Task<string> t1 = Task.Factory.StartNew<string>(() =>
    {
        Console.WriteLine("task1");
        return "task1";
    });
 
    Task<string> t2 = Task.Factory.StartNew<string>(() =>
    {
        Console.WriteLine("task2");
        return "task2";
    });
 
    Task.Factory.ContinueWhenAll(new Task[] { t1, t2 }, t =>
    {
        string s = "ContinueWhenAll:";
        foreach (Task<string> item in t)
        {
            s += item.Result;
        }
        Console.WriteLine(s);
    });
}

  运行结果:

C# Task详解第15张

 2.ContinueWhenAny

相当于回调

效果其实和WhenAny差不多,只不过ContineWhenAny采用了回调的方式

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static void fun18()
{
    Task<string> t1 = Task.Factory.StartNew<string>(() =>
    {
        Thread.Sleep(10);
        Console.WriteLine("task1");
        return "task1";
    });
 
    Task<string> t2 = Task.Factory.StartNew<string>(() =>
    {
        Console.WriteLine("task2");
        return "task2";
    });
 
    Task.Factory.ContinueWhenAny(new Task[] { t1, t2 }, t =>
    {
        Console.WriteLine($"{(t as Task<string>).Result} 先执行完");
    });
}

  执行结果:

C# Task详解第16张

 3.FromAsync

相当于异步委托的精简写法,其中ContinueWith相当于异步委托中的callback

使用:

public Task<TResult> FromAsync<TArg1, TResult>(Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod, Func<IAsyncResult, TResult> endMethod, TArg1 arg1, object state);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
static void Main(string[] args)
{
    fun20();
 
    Console.WriteLine("Main");
    Console.ReadKey();
}
 
private static void fun20()
{
    var func = new Func<stringstring>(x =>
    {
        Thread.Sleep(1000);
        Console.WriteLine(x);
        return "callback";
    });
 
    Task.Factory.FromAsync(func.BeginInvoke, func.EndInvoke, "func"null).ContinueWith(t =>
    {
        Console.WriteLine(t.Result);
    });
}

  运行结果:

C# Task详解第17张

参考:https://www.cnblogs.com/zhaoshujie/p/11082753.html
https://www.cnblogs.com/yaosj/p/10342883.html

免责声明:文章转载自《C# Task详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇如何修改cmd控制台默认编码为utf-8Unreal Engine is exiting due to D3D device being lost下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

索引节点(inode)爆满问题处理

后来,我用df-I检查/data分区的索引节点,发现它已满,这导致系统无法创建新的目录和文件。inode是用于存储这些数据的信息,包括文件大小、所有者、用户组、读写权限等。inode索引每个文件的信息,因此它具有inode的值。根据指令,操作系统可以通过inode值最快找到对应的文件。故障排除的原因是/data/cache目录中有大量小字节缓存文件,这些文件...

正负无穷float('inf')的一些用法

示例:输入:[-2,1,-3,4,-1,2,1,-5,4],输出:6解释:连续子数组[4],-1,2,1]的和最大,为6。...

小程序实现单选多选功能

applet的单选组件和复选框组件的样式只提供了变化的颜色,这显然不足以满足实际的项目需求,因此您可以自己模拟。脚注:小程序不支持dom1的操作。多个框的模拟实现:实现思路:想法非常简单。使用选中的属性绑定每个选项。类型为布尔型。单击以反转!...

flutter vscode+第三方安卓模拟器

1.首先打开夜曲模拟器2.Win+R,选择cmd,在第三方模拟器安装目录的bin目录下输入夜曲模拟器,然后运行命令:nox_Adb.execonnect127.0.0.1:620013。打开项目终端的vscode并建立连接:adbconnect127.00.1:62001(夜神模拟器的默认端口)4。查看连接:adbdevices或不使用第三方模拟器:1.打开...

Fiddler抓包7-post请求(json)(转载)

2.查看上图中的红色框:这里只支持application/x-www-form-urlencoded格式的body参数,即json格式。您需要检查JOSN列中的five和xml。1.如果遇到text/xml格式的正文,如下图所示...

SQLServer2008/2012 安装、添加sa用户和密码、多实例安装、修改端口, 重启生效

因为我们无法使用sa用户登录,所以只能使用系统登录。登录后,我们需要修改相关属性。右键单击数据库,然后单击属性。在这个sa的登录属性对话框中,我们首先需要设置这个用户的密码。由于此用户名是系统的用户,我们可以直接填写密码,然后再次确认密码。然后在对话框中,单击左上角的第二个属性服务器角色。这是您要实现的添加用户的角色。...