当前位置:   article > 正文

C# Task用法_task null

task null

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

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. Task t = new Task(() =>
  11. {
  12. Console.WriteLine("任务开始工作……");
  13. //模拟工作过程
  14. Thread.Sleep(5000);
  15. });
  16. t.Start();
  17. t.ContinueWith((task) =>
  18. {
  19. Console.WriteLine("任务完成,完成时候的状态为:");
  20. Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
  21. });
  22. Console.ReadKey();
  23. }
  24. }
  25. }

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

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. var t1 = new Task(() => TaskMethod("Task 1"));
  11. var t2 = new Task(() => TaskMethod("Task 2"));
  12. t2.Start();
  13. t1.Start();
  14. Task.WaitAll(t1, t2);
  15. Task.Run(() => TaskMethod("Task 3"));
  16. Task.Factory.StartNew(() => TaskMethod("Task 4"));
  17. //标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。
  18. Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);
  19. #region 常规的使用方式
  20. Console.WriteLine("主线程执行业务处理.");
  21. //创建任务
  22. Task task = new Task(() =>
  23. {
  24. Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
  25. for (int i = 0; i < 10; i++)
  26. {
  27. Console.WriteLine(i);
  28. }
  29. });
  30. //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
  31. task.Start();
  32. Console.WriteLine("主线程执行其他处理");
  33. task.Wait();
  34. #endregion
  35. Thread.Sleep(TimeSpan.FromSeconds(1));
  36. Console.ReadLine();
  37. }
  38. static void TaskMethod(string name)
  39. {
  40. Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
  41. name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
  42. }
  43. }
  44. }

  async/await的实现方式:

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. async static void AsyncFunction()
  9. {
  10. await Task.Delay(1);
  11. Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
  12. for (int i = 0; i < 10; i++)
  13. {
  14. Console.WriteLine(string.Format("AsyncFunction:i={0}", i));
  15. }
  16. }
  17. public static void Main()
  18. {
  19. Console.WriteLine("主线程执行业务处理.");
  20. AsyncFunction();
  21. Console.WriteLine("主线程执行其他处理");
  22. for (int i = 0; i < 10; i++)
  23. {
  24. Console.WriteLine(string.Format("Main:i={0}", i));
  25. }
  26. Console.ReadLine();
  27. }
  28. }
  29. }

  带返回值的方式
  方式4:
  Task<int> task = CreateTask("Task 1");
  task.Start(); 
  int result = task.Result;

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static Task<int> CreateTask(string name)
  9. {
  10. return new Task<int>(() => TaskMethod(name));
  11. }
  12. static void Main(string[] args)
  13. {
  14. TaskMethod("Main Thread Task");
  15. Task<int> task = CreateTask("Task 1");
  16. task.Start();
  17. int result = task.Result;
  18. Console.WriteLine("Task 1 Result is: {0}", result);
  19. task = CreateTask("Task 2");
  20. //该任务会运行在主线程中
  21. task.RunSynchronously();
  22. result = task.Result;
  23. Console.WriteLine("Task 2 Result is: {0}", result);
  24. task = CreateTask("Task 3");
  25. Console.WriteLine(task.Status);
  26. task.Start();
  27. while (!task.IsCompleted)
  28. {
  29. Console.WriteLine(task.Status);
  30. Thread.Sleep(TimeSpan.FromSeconds(0.5));
  31. }
  32. Console.WriteLine(task.Status);
  33. result = task.Result;
  34. Console.WriteLine("Task 3 Result is: {0}", result);
  35. #region 常规使用方式
  36. //创建任务
  37. Task<int> getsumtask = new Task<int>(() => Getsum());
  38. //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
  39. getsumtask.Start();
  40. Console.WriteLine("主线程执行其他处理");
  41. //等待任务的完成执行过程。
  42. getsumtask.Wait();
  43. //获得任务的执行结果
  44. Console.WriteLine("任务执行结果:{0}", getsumtask.Result.ToString());
  45. #endregion
  46. }
  47. static int TaskMethod(string name)
  48. {
  49. Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
  50. name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
  51. Thread.Sleep(TimeSpan.FromSeconds(2));
  52. return 42;
  53. }
  54. static int Getsum()
  55. {
  56. int sum = 0;
  57. Console.WriteLine("使用Task执行异步操作.");
  58. for (int i = 0; i < 100; i++)
  59. {
  60. sum += i;
  61. }
  62. return sum;
  63. }
  64. }
  65. }

    async/await的实现:

  1. using System;
  2. using System.Threading.Tasks;
  3. namespace ConsoleApp1
  4. {
  5. class Program
  6. {
  7. public static void Main()
  8. {
  9. var ret1 = AsyncGetsum();
  10. Console.WriteLine("主线程执行其他处理");
  11. for (int i = 1; i <= 3; i++)
  12. Console.WriteLine("Call Main()");
  13. int result = ret1.Result; //阻塞主线程
  14. Console.WriteLine("任务执行结果:{0}", result);
  15. }
  16. async static Task<int> AsyncGetsum()
  17. {
  18. await Task.Delay(1);
  19. int sum = 0;
  20. Console.WriteLine("使用Task执行异步操作.");
  21. for (int i = 0; i < 100; i++)
  22. {
  23. sum += i;
  24. }
  25. return sum;
  26. }
  27. }
  28. }

  2.2、组合任务.ContinueWith
   简单Demo:

  1. using System;
  2. using System.Threading.Tasks;
  3. namespace ConsoleApp1
  4. {
  5. class Program
  6. {
  7. public static void Main()
  8. {
  9. //创建一个任务
  10. Task<int> task = new Task<int>(() =>
  11. {
  12. int sum = 0;
  13. Console.WriteLine("使用Task执行异步操作.");
  14. for (int i = 0; i < 100; i++)
  15. {
  16. sum += i;
  17. }
  18. return sum;
  19. });
  20. //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
  21. task.Start();
  22. Console.WriteLine("主线程执行其他处理");
  23. //任务完成时执行处理。
  24. Task cwt = task.ContinueWith(t =>
  25. {
  26. Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());
  27. });
  28. task.Wait();
  29. cwt.Wait();
  30. }
  31. }
  32. }

   任务的串行:

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace ConsoleApp1
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. ConcurrentStack<int> stack = new ConcurrentStack<int>();
  12. //t1先串行
  13. var t1 = Task.Factory.StartNew(() =>
  14. {
  15. stack.Push(1);
  16. stack.Push(2);
  17. });
  18. //t2,t3并行执行
  19. var t2 = t1.ContinueWith(t =>
  20. {
  21. int result;
  22. stack.TryPop(out result);
  23. Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
  24. });
  25. //t2,t3并行执行
  26. var t3 = t1.ContinueWith(t =>
  27. {
  28. int result;
  29. stack.TryPop(out result);
  30. Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
  31. });
  32. //等待t2和t3执行完
  33. Task.WaitAll(t2, t3);
  34. //t7串行执行
  35. var t4 = Task.Factory.StartNew(() =>
  36. {
  37. Console.WriteLine("当前集合元素个数:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
  38. });
  39. t4.Wait();
  40. }
  41. }
  42. }

  子任务:

  1. using System;
  2. using System.Threading.Tasks;
  3. namespace ConsoleApp1
  4. {
  5. class Program
  6. {
  7. public static void Main()
  8. {
  9. Task<string[]> parent = new Task<string[]>(state =>
  10. {
  11. Console.WriteLine(state);
  12. string[] result = new string[2];
  13. //创建并启动子任务
  14. new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();
  15. new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();
  16. return result;
  17. }, "我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。");
  18. //任务处理完成后执行的操作
  19. parent.ContinueWith(t =>
  20. {
  21. Array.ForEach(t.Result, r => Console.WriteLine(r));
  22. });
  23. //启动父任务
  24. parent.Start();
  25. //等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束
  26. //parent.Wait();
  27. Console.ReadLine();
  28. }
  29. }
  30. }

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

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Node
  7. {
  8. public Node Left { get; set; }
  9. public Node Right { get; set; }
  10. public string Text { get; set; }
  11. }
  12. class Program
  13. {
  14. static Node GetNode()
  15. {
  16. Node root = new Node
  17. {
  18. Left = new Node
  19. {
  20. Left = new Node
  21. {
  22. Text = "L-L"
  23. },
  24. Right = new Node
  25. {
  26. Text = "L-R"
  27. },
  28. Text = "L"
  29. },
  30. Right = new Node
  31. {
  32. Left = new Node
  33. {
  34. Text = "R-L"
  35. },
  36. Right = new Node
  37. {
  38. Text = "R-R"
  39. },
  40. Text = "R"
  41. },
  42. Text = "Root"
  43. };
  44. return root;
  45. }
  46. static void Main(string[] args)
  47. {
  48. Node root = GetNode();
  49. DisplayTree(root);
  50. }
  51. static void DisplayTree(Node root)
  52. {
  53. var task = Task.Factory.StartNew(() => DisplayNode(root),
  54. CancellationToken.None,
  55. TaskCreationOptions.None,
  56. TaskScheduler.Default);
  57. task.Wait();
  58. }
  59. static void DisplayNode(Node current)
  60. {
  61. if (current.Left != null)
  62. Task.Factory.StartNew(() => DisplayNode(current.Left),
  63. CancellationToken.None,
  64. TaskCreationOptions.AttachedToParent,
  65. TaskScheduler.Default);
  66. if (current.Right != null)
  67. Task.Factory.StartNew(() => DisplayNode(current.Right),
  68. CancellationToken.None,
  69. TaskCreationOptions.AttachedToParent,
  70. TaskScheduler.Default);
  71. Console.WriteLine("当前节点的值为{0};处理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
  72. }
  73. }
  74. }

  2.3、取消任务 CancellationTokenSource

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. private static int TaskMethod(string name, int seconds, CancellationToken token)
  9. {
  10. Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
  11. name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
  12. for (int i = 0; i < seconds; i++)
  13. {
  14. Thread.Sleep(TimeSpan.FromSeconds(1));
  15. if (token.IsCancellationRequested) return -1;
  16. }
  17. return 42 * seconds;
  18. }
  19. private static void Main(string[] args)
  20. {
  21. var cts = new CancellationTokenSource();
  22. var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
  23. Console.WriteLine(longTask.Status);
  24. cts.Cancel();
  25. Console.WriteLine(longTask.Status);
  26. Console.WriteLine("First task has been cancelled before execution");
  27. cts = new CancellationTokenSource();
  28. longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
  29. longTask.Start();
  30. for (int i = 0; i < 5; i++)
  31. {
  32. Thread.Sleep(TimeSpan.FromSeconds(0.5));
  33. Console.WriteLine(longTask.Status);
  34. }
  35. cts.Cancel();
  36. for (int i = 0; i < 5; i++)
  37. {
  38. Thread.Sleep(TimeSpan.FromSeconds(0.5));
  39. Console.WriteLine(longTask.Status);
  40. }
  41. Console.WriteLine("A task has been completed with result {0}.", longTask.Result);
  42. }
  43. }
  44. }

  2.4、处理任务中的异常
  单个任务:

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static int TaskMethod(string name, int seconds)
  9. {
  10. Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
  11. name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
  12. Thread.Sleep(TimeSpan.FromSeconds(seconds));
  13. throw new Exception("Boom!");
  14. return 42 * seconds;
  15. }
  16. static void Main(string[] args)
  17. {
  18. try
  19. {
  20. Task<int> task = Task.Run(() => TaskMethod("Task 2", 2));
  21. int result = task.GetAwaiter().GetResult();
  22. Console.WriteLine("Result: {0}", result);
  23. }
  24. catch (Exception ex)
  25. {
  26. Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);
  27. }
  28. Console.WriteLine("----------------------------------------------");
  29. Console.WriteLine();
  30. }
  31. }
  32. }

  多个任务:

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static int TaskMethod(string name, int seconds)
  9. {
  10. Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
  11. name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
  12. Thread.Sleep(TimeSpan.FromSeconds(seconds));
  13. throw new Exception(string.Format("Task {0} Boom!", name));
  14. return 42 * seconds;
  15. }
  16. public static void Main(string[] args)
  17. {
  18. try
  19. {
  20. var t1 = new Task<int>(() => TaskMethod("Task 3", 3));
  21. var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
  22. var complexTask = Task.WhenAll(t1, t2);
  23. var exceptionHandler = complexTask.ContinueWith(t =>
  24. Console.WriteLine("Result: {0}", t.Result),
  25. TaskContinuationOptions.OnlyOnFaulted
  26. );
  27. t1.Start();
  28. t2.Start();
  29. Task.WaitAll(t1, t2);
  30. }
  31. catch (AggregateException ex)
  32. {
  33. ex.Handle(exception =>
  34. {
  35. Console.WriteLine(exception.Message);
  36. return true;
  37. });
  38. }
  39. }
  40. }
  41. }

    async/await的方式:

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static async Task ThrowNotImplementedExceptionAsync()
  9. {
  10. throw new NotImplementedException();
  11. }
  12. static async Task ThrowInvalidOperationExceptionAsync()
  13. {
  14. throw new InvalidOperationException();
  15. }
  16. static async Task Normal()
  17. {
  18. await Fun();
  19. }
  20. static Task Fun()
  21. {
  22. return Task.Run(() =>
  23. {
  24. for (int i = 1; i <= 10; i++)
  25. {
  26. Console.WriteLine("i={0}", i);
  27. Thread.Sleep(200);
  28. }
  29. });
  30. }
  31. static async Task ObserveOneExceptionAsync()
  32. {
  33. var task1 = ThrowNotImplementedExceptionAsync();
  34. var task2 = ThrowInvalidOperationExceptionAsync();
  35. var task3 = Normal();
  36. try
  37. {
  38. //异步的方式
  39. Task allTasks = Task.WhenAll(task1, task2, task3);
  40. await allTasks;
  41. //同步的方式
  42. //Task.WaitAll(task1, task2, task3);
  43. }
  44. catch (NotImplementedException ex)
  45. {
  46. Console.WriteLine("task1 任务报错!");
  47. }
  48. catch (InvalidOperationException ex)
  49. {
  50. Console.WriteLine("task2 任务报错!");
  51. }
  52. catch (Exception ex)
  53. {
  54. Console.WriteLine("任务报错!");
  55. }
  56. }
  57. public static void Main()
  58. {
  59. Task task = ObserveOneExceptionAsync();
  60. Console.WriteLine("主线程继续运行........");
  61. task.Wait();
  62. }
  63. }
  64. }

  2.5、Task.FromResult的应用

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace ConsoleApp1
  6. {
  7. class Program
  8. {
  9. static IDictionary<string, string> cache = new Dictionary<string, string>()
  10. {
  11. {"0001","A"},
  12. {"0002","B"},
  13. {"0003","C"},
  14. {"0004","D"},
  15. {"0005","E"},
  16. {"0006","F"},
  17. };
  18. public static void Main()
  19. {
  20. Task<string> task = GetValueFromCache("0006");
  21. Console.WriteLine("主程序继续执行。。。。");
  22. string result = task.Result;
  23. Console.WriteLine("result={0}", result);
  24. }
  25. private static Task<string> GetValueFromCache(string key)
  26. {
  27. Console.WriteLine("GetValueFromCache开始执行。。。。");
  28. string result = string.Empty;
  29. //Task.Delay(5000);
  30. Thread.Sleep(5000);
  31. Console.WriteLine("GetValueFromCache继续执行。。。。");
  32. if (cache.TryGetValue(key, out result))
  33. {
  34. return Task.FromResult(result);
  35. }
  36. return Task.FromResult("");
  37. }
  38. }
  39. }

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

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. static void DoProcessing(IProgress<int> progress)
  9. {
  10. for (int i = 0; i <= 100; ++i)
  11. {
  12. Thread.Sleep(100);
  13. if (progress != null)
  14. {
  15. progress.Report(i);
  16. }
  17. }
  18. }
  19. static async Task Display()
  20. {
  21. //当前线程
  22. var progress = new Progress<int>(percent =>
  23. {
  24. Console.Clear();
  25. Console.Write("{0}%", percent);
  26. });
  27. //线程池线程
  28. await Task.Run(() => DoProcessing(progress));
  29. Console.WriteLine("");
  30. Console.WriteLine("结束");
  31. }
  32. public static void Main()
  33. {
  34. Task task = Display();
  35. task.Wait();
  36. }
  37. }
  38. }

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

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. private delegate string AsynchronousTask(string threadName);
  9. private static string Test(string threadName)
  10. {
  11. Console.WriteLine("Starting...");
  12. Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
  13. Thread.Sleep(TimeSpan.FromSeconds(2));
  14. Thread.CurrentThread.Name = threadName;
  15. return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
  16. }
  17. private static void Callback(IAsyncResult ar)
  18. {
  19. Console.WriteLine("Starting a callback...");
  20. Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
  21. Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
  22. Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
  23. }
  24. //执行的流程是 先执行Test--->Callback--->task.ContinueWith
  25. static void Main(string[] args)
  26. {
  27. AsynchronousTask d = Test;
  28. Console.WriteLine("Option 1");
  29. Task<string> task = Task<string>.Factory.FromAsync(
  30. d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);
  31. task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}",
  32. t.Result));
  33. while (!task.IsCompleted)
  34. {
  35. Console.WriteLine(task.Status);
  36. Thread.Sleep(TimeSpan.FromSeconds(0.5));
  37. }
  38. Console.WriteLine(task.Status);
  39. }
  40. }
  41. }

  不带回调方式的

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace ConsoleApp1
  5. {
  6. class Program
  7. {
  8. private delegate string AsynchronousTask(string threadName);
  9. private static string Test(string threadName)
  10. {
  11. Console.WriteLine("Starting...");
  12. Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
  13. Thread.Sleep(TimeSpan.FromSeconds(2));
  14. Thread.CurrentThread.Name = threadName;
  15. return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
  16. }
  17. //执行的流程是 先执行Test--->task.ContinueWith
  18. static void Main(string[] args)
  19. {
  20. AsynchronousTask d = Test;
  21. Task<string> task = Task<string>.Factory.FromAsync(
  22. d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");
  23. task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
  24. t.Result));
  25. while (!task.IsCompleted)
  26. {
  27. Console.WriteLine(task.Status);
  28. Thread.Sleep(TimeSpan.FromSeconds(0.5));
  29. }
  30. Console.WriteLine(task.Status);
  31. }
  32. }
  33. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/115731
推荐阅读
相关标签
  

闽ICP备14008679号