使用任务并行库(2)
使用任务执行基本的操作
简介
区别在线程池中和主线程中运行任务的不同之处。
以下是代码实践:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace 使用任务执行基本的操作
{
internal class Program
{
private static void Main()
{
TaskMethod("Main thead Task");//在主线程中运行函数,显示主线程信息
var task = CreateTask("Task 1");
task.Start();//任务返回前,主线程处于阻塞状态
var result = task.Result;//该语句会阻塞主线程
Console.WriteLine("Result is: {0}", result);
task = CreateTask("Task 2");
task.RunSynchronously();//运行在主线程中,和在主线程中直接调用函数完全相同
result = task.Result;
Console.WriteLine("Result is: {0}", result);
task = CreateTask("Task 3");
task.Start();//没有阻塞主线程
while (!task.IsCompleted)
{
Console.WriteLine(task.Status);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
Console.WriteLine(task.Status);
result = task.Result;
Console.WriteLine("Result is: {0}", result);
Console.ReadKey();
}
private static Task<int> CreateTask(string name)
{
return new Task<int>(() => TaskMethod(name));
}
private static int TaskMethod(string name)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
return 42;
}
}
}
总结
- RunSynchronously()该方法使任务运行在主线程中;
- Result属性会阻塞主线程,知道获得了任务结果。
备注:学习《Multithreading in C# 5.0 Cookbook》Eugene Agafonov著的总结,以备日后查询。