关闭

TPL——Task的状态及堕性Task

标签: TPLTaskC#多线程
132人阅读 评论(0) 收藏 举报
分类:
Getting the Status of a Task

One other area of standardization for parallel programming is the status information available from the Task.Status property, which returns a value from the System.Threading.Tasks.TaskStatus enumeration. The enumeration members are shown bellow.


堕性的Task:

新建一个Task进行计算,而计算的结果又不是立刻需要的时候,可以考虑使用堕性的Task,这种Task只有在其返回值被需要时才会运行。

using System;
using System.Threading.Tasks;
namespace Listing_23 {
class Listing_23 {
static void Main(string[] args) {
// define the function
Func<string> taskBody = new Func<string>(() => {
Console.WriteLine("Task body working...");
return "Task Result";
});
// create the lazy variable
Lazy<Task<string>> lazyData = new Lazy<Task<string>>(() =>
Task<string>.Factory.StartNew(taskBody));
Console.WriteLine("Calling lazy variable");
Console.WriteLine("Result from task: {0}", lazyData.Value.Result);
// do the same thing in a single statement
Lazy<Task<string>> lazyData2 = new Lazy<Task<string>>(
() => Task<string>.Factory.StartNew(() => {
Console.WriteLine("Task body working...");
return "Task Result";
}));
Console.WriteLine("Calling second lazy variable");
Console.WriteLine("Result from task: {0}", lazyData2.Value.Result);
// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();
}
}
}


0
0

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