关闭

TPL——开始一个Task

标签: TPLTaskC#C#多线程
93人阅读 评论(0) 收藏 举报
分类:

创建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();
}
}
}
在取得结果处,线程会阻塞直至结果返回。




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:47651次
    • 积分:932
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:2篇
    • 译文:1篇
    • 评论:6条
    最新评论