心清的专栏

C/C++、linux系统编程、matlab,关注机器学习,数据挖掘等领域

TPL——开始一个Task

创建Tasks的四个方式:

using System;
using System.Threading.Tasks;
namespace Listing_02 {
class Listing_02 {
static void Main(string[] args) {
// use an Action delegate and a named method
Task task1 = new Task(new Action(printMessage));
// use a anonymous delegate
Task task2 = new Task(delegate {
printMessage();
});
// use a lambda expression and a named method
Task task3 = new Task(() => printMessage());
// use a lambda expression and an anonymous method
Task task4 = new Task(() => {
printMessage();
});
task1.Start();
task2.Start();
task3.Start();
task4.Start();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
static void printMessage() {
Console.WriteLine("Hello World");
}
}
}
创建并且运行Tasks

Task.Factory.StartNew(() => {
Console.WriteLine("Hello World");
});

传递参数

using System;
using System.Threading.Tasks;
namespace Listing_03 {
class Listing_03 {
static void Main(string[] args) {
// use an Action delegate and a named method
Task task1 = new Task(new Action<object>(printMessage),
"First task");
// use a anonymous delegate
Task task2 = new Task(delegate (object obj) {
printMessage(obj);
}, "Second Task");
// use a lambda expression and a named method
// note that parameters to a lambda don’t need
// to be quoted if there is only one parameter
Task task3 = new Task((obj) => printMessage(obj), "Third task");
// use a lambda expression and an anonymous method
Task task4 = new Task((obj) => {
printMessage(obj);
}, "Fourth task");
task1.Start();
task2.Start();
task3.Start();
task4.Start();
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
static void printMessage(object message) {
Console.WriteLine("Message: {0}", message);
}
}
}

返回结果

using System;
using System.Threading.Tasks;
namespace Listing_05 {
class Listing_05 {
static void Main(string[] args) {
// create the task
Task<int> task1 = new Task<int>(() => {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
});
// start the task
task1.Start();
// write out the result
Console.WriteLine("Result 1: {0}", task1.Result);
// create the task using state
Task<int> task2 = new Task<int>(obj => {
int sum = 0;
int max = (int)obj;
for (int i = 0; i < max; i++) {
sum += i;
}
return sum;
}, 100);
// start the task
task2.Start();
// write out the result
Console.WriteLine("Result 2: {0}", task2.Result);
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}
在取得结果处,线程会阻塞直至结果返回。




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010155023/article/details/52354440
文章标签: TPL Task C# C#多线程
个人分类: Threading in C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

TPL——开始一个Task

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭