使用任务并行库执行异步任务 下面的示例演示如何通过调用 TaskFactory.StartNew 方法来创建并使用 Task 对象。

 using System;
using System.Threading;
using System.Threading.Tasks; class Example
{
static void Main()
{
Action<object> action = (object obj) =>
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}",
Task.CurrentId, obj,
Thread.CurrentThread.ManagedThreadId);
}; // Create a task but do not start it.
Task t1 = new Task(action, "alpha"); // Construct a started task
Task t2 = Task.Factory.StartNew(action, "beta");
// Block the main thread to demonstate that t2 is executing
t2.Wait(); // Launch t1
t1.Start();
Console.WriteLine("t1 has been launched. (Main Thread={0})",
Thread.CurrentThread.ManagedThreadId);
// Wait for the task to finish.
t1.Wait(); // Construct a started task using Task.Run.
String taskData = "delta";
Task t3 = Task.Run(() =>
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}",
Task.CurrentId, taskData,
Thread.CurrentThread.ManagedThreadId);
});
// Wait for the task to finish.
t3.Wait(); // Construct an unstarted task
Task t4 = new Task(action, "gamma");
// Run it synchronously
t4.RunSynchronously();
// Although the task was run synchronously, it is a good practice
// to wait for it in the event exceptions were thrown by the task.
t4.Wait();
}
}
// The example displays output like the following:
// Task=1, obj=beta, Thread=3
// t1 has been launched. (Main Thread=1)
// Task=2, obj=alpha, Thread=4
// Task=3, obj=delta, Thread=3
// Task=4, obj=gamma, Thread=1

最新文章

  1. SQL Server-聚焦APPLY运算符(二十七)
  2. Oralce中SQL删除重复数据只保留一条(转)
  3. 编程实现Linux下的ls -l
  4. pd的django To Do List教程-----3:模板的建立
  5. Sort List leetcode
  6. .NET Core资源汇总
  7. [Swift]LeetCode243.最短单词距离 $ Shortest Word Distance
  8. kubenetes master重启以后,服务异常排查
  9. JVM深入理解
  10. ssh 使用 sed 替换的时候,替换的字符串有单双引号的时候怎么用
  11. spring boot多数据源配置(mysql,redis,mongodb)实战
  12. sql行转列实例
  13. tar 命令 简易使用方法
  14. 深度学习原理与框架-猫狗图像识别-卷积神经网络(代码) 1.cv2.resize(图片压缩) 2..get_shape()[1:4].num_elements(获得最后三维度之和) 3.saver.save(训练参数的保存) 4.tf.train.import_meta_graph(加载模型结构) 5.saver.restore(训练参数载入)
  15. Linux CentOS 7的图形界面安装(GNOME、KDE等)
  16. java用字符io流复制文件
  17. LibreOJ #6000. 「网络流 24 题」搭配飞行员 最大匹配
  18. [Android] Linux下JNI简单实现过程
  19. codeforces 766E Mahmoud and a xor trip
  20. 在使用FastJson开发遇到的的坑

热门文章

  1. Linux上不了网的几个排查点
  2. go get Unknown SSL protocol error in connection to gopkg.in
  3. hihoCoder 1394 : 网络流四&#183;最小路径覆盖
  4. Grunt: 拼接代码,js丑化(压缩),css压缩,html压缩,观察文件,拷贝文件,删除文件,压缩文件
  5. Docker Swarm 介绍 or 工作原理
  6. Python RabbitMQ消息持久化
  7. echarts2.0tooltip边框限制导致tooltip显示不全解决办法
  8. TTS 语音修复 ,缺少文件的,没注册类的
  9. WEB 前端插件整理
  10. 文件下载 路径中有中文 报错 提示 文件找不到 java.io.FileNotFoundException: http://192.168.1.141:8096/resources/card/comcard/????????/????????.png