C#中控制線程池的執行順序 autoEvent.WaitOne();


在使用線程池時,當用線程池執行多個任務時,由於執行的任務時間過長,會導制兩個任務互相執行,如果兩個任務具有一定的操作順序,可能會導制不同的操作結果,這時,就要將線程池按順序操作。

不按順序對線程池進行操作,代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace c_sharp_thread_pool_test
{
    class Program
    {
        static void Main(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(thread_method),autoEvent);
            ThreadPool.QueueUserWorkItem(new WaitCallback(work_method),autoEvent);
            Console.ReadLine();
        }

        static void thread_method(object stateInfo)
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine("i={0}_thread_method:{1}",i,Thread.CurrentThread.IsThreadPoolThread?"":"not");
        }
        static void work_method(object stateInfo)
        {
            for(int i=0;i<10;i++)
            {
                Console.WriteLine("work_method,i={0}",i);
            }
        }
    }
}

//

用AutoResetEvent類來實現的順序執行

可以用AutoResetEvent類的WaitOne方法阻止線程,然后只執行當前操作的線程池,當遇到AutoResetEvent類的Set方法后,將當前線程設置為終止狀態,執行其他等待的線程。代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace c_sharp_thread_pool_test
{
    class Program
    {
        static void Main(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(thread_method),autoEvent);

            //
            autoEvent.WaitOne();
            ThreadPool.QueueUserWorkItem(new WaitCallback(work_method),autoEvent);
            //
            autoEvent.WaitOne();
            Console.ReadLine();
        }

        static void thread_method(object stateInfo)
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine("i={0}_thread_method:{1}",i,Thread.CurrentThread.IsThreadPoolThread?"":"not");
            //
            ((AutoResetEvent)stateInfo).Set();
        }
        static void work_method(object stateInfo)
        {
            for(int i=0;i<10;i++)
            {
                Console.WriteLine("work_method,i={0}",i);
                //
                ((AutoResetEvent)stateInfo).Set();
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM