基于任务的异步编程
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-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?