基于任务的异步编程
2022/7/2 1:24:02
本文主要是介绍基于任务的异步编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
创建任务
Task.Factory.StartNew
线程池
等待任务
Task.WaitAll(taskArray);
using System; using System.Threading; using System.Threading.Tasks; class CustomData { public long CreationTime; public int Name; public int ThreadNum; } public class Example { public static void Main() { Task[] taskArray = new Task[10]; for (int i = 0; i < taskArray.Length; i++) { taskArray[i] = Task.Factory.StartNew( (Object obj ) => { CustomData data = obj as CustomData; if (data == null) return; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; }, new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks} ); } Task.WaitAll(taskArray); foreach (var task in taskArray) { var data = task.AsyncState as CustomData; if (data != null) Console.WriteLine("Task #{0} created at {1}, ran on thread #{2}.", data.Name, data.CreationTime, data.ThreadNum); } } } // The example displays output like the following: // Task #0 created at 635116412924597583 on thread #3. // Task #1 created at 635116412924607584 on thread #4. // Task #3 created at 635116412924607584 on thread #4. // Task #4 created at 635116412924607584 on thread #4. // Task #2 created at 635116412924607584 on thread #3. // Task #6 created at 635116412924607584 on thread #3. // Task #5 created at 635116412924607584 on thread #4. // Task #8 created at 635116412924607584 on thread #4. // Task #7 created at 635116412924607584 on thread #3. // Task #9 created at 635116412924607584 on thread #4.
嵌套子任务
线程套线程,创建线城市添加TaskCreationOptions.AttachedToParent配置,这样子任务完成父任务才会完成
官方推荐分离子任务即个玩个的
using System; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { var parent = Task.Factory.StartNew(() => { Console.WriteLine("Parent task executing."); var child = Task.Factory.StartNew(() => { Console.WriteLine("Attached child starting."); Thread.SpinWait(5000000); Console.WriteLine("Attached child completing."); }, TaskCreationOptions.AttachedToParent); }); parent.Wait(); Console.WriteLine("Parent has completed."); } } // The example displays the following output: // Parent task executing. // Attached child starting. // Attached child completing. // Parent has completed.
参考
- https://docs.microsoft.com/zh-cn/dotnet/standard/parallel-programming/task-based-asynchronous-programming
- https://docs.microsoft.com/zh-cn/dotnet/standard/parallel-programming/attached-and-detached-child-tasks
这篇关于基于任务的异步编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南