Used. NET thread pool programmers know that by invoking the QueueUserWorkItem method of the ThreadPool class, the code to be executed is put into the thread pool to execute. Because of the power of the. NET FCL, this operation is extremely easy to make. But there is an obvious disadvantage of using the thread pool, which is that we cannot get the return value of the threads pool execution method because the return value of the WaitCallback delegate is void. Note: The prototype for the WaitCallback delegate is: public delegate void WaitCallback (Object state).
For example, we have a method code like this:
public int Sum()
{
//此方法模拟一个耗时操作
int sum = 0;
for (int num = 1; num <= 100; num++)
{
Thread.Sleep(5);
sum += num;
}
return sum;
}
If this method can be added to the thread pool to execute (not actually, because it does not match the WaitCallback delegate), we cannot get the result of execution. With. NET4.0 's release, this problem is resolved,. NET 4.0 provides a new feature called Task, under the System.Threading.Task namespace, there is a task class and its generic version of Task<tresult>. We can add this method to the task and get the execution result, the schematic code is as follows:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskDemo
{
class Program
{
static void Main(string[] args)
{
Task<int> task = new Task<int>(() => Sum());//新建任务实例
task.Start();//开始任务
Console.WriteLine("任务已开始");
task.Wait();//等待任务执行完成
Console.WriteLine(task.Result);
}
//此方法模拟一个耗时操作
static int Sum()
{
Console.WriteLine("任务正在执行");
int sum = 0;
for (int num = 1; num <= 100; num++)
{
Thread.Sleep(5);
sum += num;
}
return sum;
}
}
}
Tasks (Task) is a good thing indeed! This is a preliminary introduction to Tasks (Task) only. Because I also just contact, feel this is a very useful function, so can not help to write out, due to the author's limited level, the shortcomings are also looking at the master guidance.
Finally, thank Jeffrey Richter for the surprise--"CLR via C #, third Edition."