首页 > 代码库 > 使用 Task 替换 ThreadPool ,异步监测所有线程(任务)是否全部执行完毕

使用 Task 替换 ThreadPool ,异步监测所有线程(任务)是否全部执行完毕

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Ex.RulesTester.Threads
{
    /// <summary>
    /// 异步等待所有线程结束通知测试
    /// </summary>
    [TestClass]
    public class TaskAllCompleteTester
    {
        [TestMethod]
        public void TestTaskPoolStatus()
        {
            //运行异步多任务
            TaskTest.RunTask();
            var list = TaskTest.SuccessList;
            bool isAllComplete = false;
            //等待异步通知
            while (!isAllComplete)
            {
                isAllComplete = TaskTest.IsAllComplete;
                list = TaskTest.SuccessList;
            }

            Assert.IsTrue(true);
        }
        /// <summary>
        /// 对于 task 多任务执行的封装
        /// </summary>
        private class TaskTest
        {
            private static object m_lock = new object();
            public static List<string> SuccessList = new List<string>();
            private static string msg = "";
            public static bool IsFinish = false;
            public static List<Task> TaskList = new List<Task>();
            static bool isAllComplete = false;
            /// <summary>
            /// 标记所有任务是否全部执行完毕
            /// </summary>
            public static bool IsAllComplete
            {
                get { return isAllComplete; }
            }

            private TaskTest()
            {

            }

            public static void RunTask()
            {
                //运行5个任务
                for (int i = 1; i <= 5; i++)
                {
                    var task = Task.Factory.StartNew(DoTask, i);
                    TaskList.Add(task);
                }
                //异步等待所有任务执行完毕
                Task.Factory.StartNew(x =>
                {
                    Task.WaitAll(TaskList.ToArray());
                    //标记所有任务运行完成
                    isAllComplete = true;
                }, null);
            }
            private static void DoTask(object par)
            {
                Thread.Sleep(int.Parse(par.ToString()) * 1000);
                lock (m_lock)
                {
                    SuccessList.Add("Has Completed T" + par.ToString());
                }
            }

        }
    }
}

 

使用 Task 替换 ThreadPool ,异步监测所有线程(任务)是否全部执行完毕