Skip to content

使用 Task 代替 ThreadPool

ThreadPool 相对于 Thread 具有很多优势,但是 ThreadPool 在使用上却有一定的不方便。

  • ThreadPool 不支持线程的取消、完成、失败通知等交互性操作

  • ThreadPool 不支持线程执行的先后顺序

FCL 中提供了一个更强大的概念:TaskTask 在线程池的基础上进行了优化,并提供了更多的 API。

示例 1(完成通知)

cs
using System;
using System.Threading;
using System.Threading.Tasks;

namespace TaskSample
{
    class Program
    {
        static void Main(string args)
        {
            Task t = new Task(() =>
            {
                Console.WriteLine("任务开始工作");
                // 模拟工作过程
                Thread.Sleep(5000);
            });
            t.Start();
            t.ContinueWith((task) =>
            {
                Console.WriteLine("任务完成,完成时候的状态为:");
                Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", 
                    task.IsCanceled, 
                    task.IsCompleted, 
                    task.IsFaulted);
            });
            Console.ReadLine();
        }
    }
}

示例 1 输出结果

任务开始工作
任务完成,完成时候的状态为:
IsCanceled=False        IsCompleted=True        IsFaulted=False

示例 2(完成通知、取消、获取任务返回值)

cs
using System;
using System.Threading;
using System.Threading.Tasks;

namespace TaskSample2
{
    class Program
    {
        static void Main(string args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Task<int> task = new Task<int>(() => Add(cts.Token), cts.Token);
            task.Start();
            task.ContinueWith(TaskEnded);
            // 等待按任意键取消任务
            Console.ReadKey();
            cts.Cancel();
            Console.ReadKey();
        }

        static int Add(CancellationToken ct)
        {
            Console.WriteLine("任务开始 ......");
            int result = 0;
            while (!ct.IsCancellationRequested)
            {
                result++;
                Thread.Sleep(100);
            }
            return result;
        }

        static void TaskEnded(Task<int> task)
        {
            Console.WriteLine("任务完成,完成时候的状态为:");
            Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}",
                task.IsCanceled,
                task.IsCompleted,
                task.IsFaulted);
            Console.WriteLine("任务的返回值为:{0}", task.Result);
        }
    }
}

示例 2 输出结果

任务开始 ......
任务完成,完成时候的状态为:
IsCanceled=False        IsCompleted=True        IsFaulted=False
任务的返回值为:30

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.