Task案例1-處理多個任務

需求:如今有100數據須要處理,但只能啓用8個任務處理。oop

namespace TTask1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] TaskNames = new string[100];
            Task[] Tasks = new Task[8];
            for(int i = 0; i< TaskNames.Length; i++)
            {
                TaskNames[i] = "Task" + i;
            }
            int j = 0;
            int taskLoop = 100 % 8 == 0 ? 100 / 8 : 100 / 8 + 1;
            for (int i = 0; i < taskLoop; i++)
            {
                for(int m = 0; m < 8 && j+m < 100; m++)
                {
                    TMyTask MyTask = new TMyTask();
                    MyTask.TaskName = TaskNames[j+m];
                    Tasks[m] = new Task(MyTask.DoWork);
                    Tasks[m].Start();
                }
                //等待當前8個任務完成,而後進入下個循環,從新建立新的8個任務
                for (int m = 0; m < 8; m++)
                {
                    Tasks[m].Wait();
                }
                j = 8*(i+1);
                Console.WriteLine("Four Tasks Finished");
            }            
            Console.WriteLine("All Tasks Finished");
            Console.ReadKey();
        }
    }

    class TMyTask
    {
        public string TaskName { set; get; }
        //耗時任務
        public void DoWork()
        {
            Console.WriteLine("任務 " + TaskName +"開始");
            Thread.Sleep(100);
            Console.WriteLine("任務 " + TaskName + "結束");
        }
    }
}
相關文章
相關標籤/搜索