Asynchronous multi-threading (c) ThreadPool

concept

The reason the thread pool birth : Thread is too strong, you can not control the number of pipe threads.

 

, You need a pool if an object creation and destruction costs relatively high, but this object also can be used repeatedly

Save more of these objects, the time needed to obtain from the pool inside; exhausted after not destroyed, returned to the pool; ( Flyweight )

Saving resources to improve performance; In addition, the total number of control can prevent abuse;

 

Start a thread pool thread method

 

method one

 

ThreadPool.QueueUserWorkItem(

 

o=> this.DoSomethingLong("btnThreadPool_Click1"));

 

Method Two

 

ThreadPool.QueueUserWorkItem(

 

o=> this.DoSomethingLong("btnThreadPool_Click2"), "嘿嘿");

 

 

 

Gets the number of thread pool threads

 

  Get maximum number of threads the thread pool

 

ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);

 

 

 

  Get the minimum number of threads in the thread pool

 

ThreadPool.GetMinThreads(out intworkerThreadsMin, out int completionPortThreadsMin);

 

Set the thread pool maximum number of threads

 

ThreadPool.SetMaxThreads (8, 8); // set maximum must be greater than CPU core number, otherwise set invalid

 

Set the minimum number of thread pool threads

 

ThreadPool.SetMinThreads(2, 2);

 

 

Note: The number of thread pool threads here are global settings, please set the time must be handled with care

For example, you set the maximum number of threads is 8, then your entire project, you can only run eight threads.

 

 

 

Setting thread pool thread to wait

 

  ManualResetEvent mre = new ManualResetEvent(false);

 

  // false --- closed --- Set open --- true --- WaitOne can pass

 

  // true --- open --ReSet closed --- false - WaitOne can only wait

 

  ThreadPool.QueueUserWorkItem(o =>

 

  {

 

      this.DoSomethingLong("btnThreadPool_Click1");

 

      mre.Set();

 

  });

 

  MrekWaitOne ();

 

  Console.WriteLine ( " task has been completed ... ");

 

The following is the complete code example

 

        //ThreadPool 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {


            #region 启动线程池
            //启动ThreadPool方式一
            ThreadPool.QueueUserWorkItem(s => Console.WriteLine("button1_Click"));
            //启动ThreadPool方式二
            ThreadPool.QueueUserWorkItem(s => Console.WriteLine("button1_Click"Hey")," );
             #Endregion 

            #region obtaining maximum and minimum thread pool threads 
            ThreadPool.GetMaxThreads ( OUT  int workerThreads, OUT  int completionPortThreads); 
            Console.WriteLine ($ " this computer is the maximum workerThreads {workerThreads}, is the maximum completionPortThreads completionPortThreads} { " ) ; 

            ThreadPool.GetMinThreads ( OUT  int workerThreadsMini, OUT  int completionPortThreadsMini); 
            Console.WriteLine ($ " this computer is the minimum workerThreadsMini {workerThreadsMini}, is the minimum completionPortThreadsMini completionPortThreadsMini} { ");
             #Endregion 

            #region set the thread pool number (maximum and minimum) threads, the number of thread pool setting process is global,
             // entrust the asynchronous call --Task - Parrallel - async / await are all thread pool threads
             / / If the maximum number of threads less than the minimum set current computer, it is not effective. 
            ThreadPool.SetMaxThreads ( . 8 , . 8 ); 
            ThreadPool.GetMaxThreads ( OUT  int workerThreads, OUT  int completionPortThreads); 
            Console.WriteLine ($ " this computer is the maximum workerThreads {workerThreads}, is the maximum completionPortThreads completionPortThreads} { " ); 

            ThreadPool.SetMinThreads ( 1 , 1 );
            ThreadPool.GetMinThreads ( OUT  int workerThreadsMini, OUT  int completionPortThreadsMini); 
            Console.WriteLine ($ " this computer is the minimum workerThreadsMini {workerThreadsMini}, is the minimum completionPortThreadsMini completionPortThreadsMini} { " );
             #endregion 


            #region disposed thread pool threads waiting for 
            the ManualResetEvent ManualReset = new new ManualResetEvent ( false );
             /// / false --- closed --- Set --- true --- WaitOne will be able to open by
             /// / open --ReSet close to true --- --- false - WaitOne can only wait 
            ThreadPool.QueueUserWorkItem (s =>
            { 
                The this .DoSomethingLong ( " the button1_Click " ); 
                manualReset.Set (); 
            }); 
            manualReset.WaitOne (); 
            Console.WriteLine ( " do after waiting for something " ); 

            #endregion 

        } 
        #region Private Method,
         ///  <Summary > 
        /// a private method is time-consuming and resource intensive
         ///  </ Summary> 
        ///  <param name = "name"> </ param> 
        private  void DoSomethingLong ( String name) 
        { 
            Console.WriteLine($"****************DoSomethingLong Start  {name} " +
                $" {Thread.CurrentThread.ManagedThreadId.ToString("00")} " +
                $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
            long lResult = 0;
            for (int i = 0; i < 1_000_000_000; i++)
            {
                lResult += i;
            }
            //Thread.Sleep(2000);

            Console.WriteLine($"****************DoSomethingLong   End  {name} " +
                $" {Thread.CurrentThread.ManagedThreadId.ToString("00")} " +
                $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} " +
                $"{lResult}***************");
        }
        #endregion

 

Guess you like

Origin www.cnblogs.com/JohnTang/p/10991807.html