C # Multithreading--A detailed description of the thread pool

Source: Internet
Author: User
LinePool System.Threading.ThreadPool, which can be used to send work items, handle asynchronous I/O, wait on behalf of other threads, and process timers. Basic usage:

        public void Main ()        {            threadpool.queueuserworkitem (jobforathread);//Give a job to the thread pool}void jobforathread (object State)//The work to be performed by the thread: satisfies the delegate waitcallback        {for (int i = 1; I <= 5; i++)            {                Console.WriteLine ("Running thread {0}, Step {1} ", Thread.CurrentThread.ManagedThreadId, i);                Thread.Sleep (+);            }        }

After the ThreadPool.QueueUserWorkItem () method is executed, the processor automatically selects a thread in the pool to handle the "work content."

1. If the thread pool is not running, a thread pool is created and the first thread is started.

2. If the thread pool is already running and has at least one idle thread, the thread pool will hand over the "work" to this idle thread for processing.

3. If the thread pool does not have idle threads at that time, the work will be in a wait state until there are idle threads to process it.

Pass The Threadpool.getmaxthreads () method to retrieve the number of thread pool requests that can be active at the same time.

            int vworkerthreads; int vcompletionportthreads;            Threadpool.getmaxthreads (out vworkerthreads, out vcompletionportthreads);            Console.WriteLine ("The maximum number of worker threads in the pool {0}, the maximum number of asynchronous I/O threads in the pool {1}", Vworkerthreads, Vcompletionportthreads);

You can set the number of thread pool requests that can be active at the same time through the Threadpool.setmaxthreads () method.

Threadpool.setmaxthreads (5, 4);

However, you cannot set the number of worker threads or the number of asynchronous I/O completion threads to less than the number of computer processors. Thread pooling is simple, but with some limitations:

1. All threads in the thread pool are background threads. If all foreground threads of the process are ended, all background threads will stop. You cannot change the thread of a pool into a foreground thread.

2. You cannot set a priority or name for a thread that is in the pool.

3. The thread that is pooled can only be used for tasks that are short in time. If a thread is to run all the time, you should create a thread using the thread class.

to jobforathread () Task pass parameter object state, call:

        public void Main ()        {            ThreadPool.QueueUserWorkItem (Jobforathread, "This is the parameter passed to the work content");//Add work at the same time, Pass parameter Console.readkey (); Let the main thread wait, otherwise "flash over"        }void jobforathread (object state)         {            Console.WriteLine ("received message: {0}", (string) state); Processing incoming data for (int i = 1; I <= 5; i++)            {                               Console.WriteLine ("Running Thread {0},step {1}", Thread.CurrentThread. Managedthreadid, i);                Thread.Sleep (+);            }        }

Simple control Operation

case, "work" is left out of control after it is given to the thread pool. It is automatically determined by the processor when the execution starts (and of course there are idle threads). You can use the following code to make the work after the specified time.

        ManualResetEvent mmanualevent;public void Main ()        {            mmanualevent = new ManualResetEvent (false); Example ThreadPool.QueueUserWorkItem (jobforathread);            Console.WriteLine ("{0} task has been given to the thread pool, but it has not been executed.", DateTime.Now.ToString ("HH:mm:ss"));            Thread.Sleep (10000); Wait for 10smmanualevent.set ();  Signals that the thread will continue to execute                       console.readkey ();//Let the main thread wait, otherwise "flash over"        }void jobforathread (object state)         {            Mmanualevent.waitone (); Wait for "mmanualevent.set ();" This sentence executes (sends a signal) Console.WriteLine ("{0} now begins to perform tasks.", DateTime.Now.ToString ("HH:mm:ss")); for ( int i = 1; I <= 5; i++)            {                               Console.WriteLine ("Running Thread {0},step {1}", Thread.CurrentThread.ManagedThreadId, i);                Thread.Sleep (+);            }        }

Operation Result:

Here, when the work is done to the thread pool, the threads are stuck in mmanualevent.waitone (); This sentence, until the main thread after 10s signaled, the work continues to execute the subsequent code. This is a "dummy start" control operation, which essentially does not allow the assignment to start working at the desired time. Here, when initializing the ManualResetEvent object, the parameter false indicates that the signal is set to "blocked state" by default, through code mmanualevent.set () , and the signal is set to "sustainable". Conversely, you can Mmanualevent.reset () by code and set the thread to "blocked state".

There is a need to wait until all threads in the thread pool have finished executing before proceeding with some other code.

        Autoresetevent[] mautoresetevent;public void Main () {mautoresetevent = new autoresetevent[]{new  AutoResetEvent (FALSE),//The default signal is block new AutoResetEvent (false), new AutoResetEvent (FALSE)};for (int i = 0; i < 3;                i++)//creation of 3 jobs {thread.sleep (1000);             ThreadPool.QueueUserWorkItem (Jobforathread, i);            } Console.WriteLine ("All work has been added to the pool ..."); WaitHandle.WaitAll (mautoresetevent);            After waiting for all signals in the mautoresetevent to continue, follow the code Console.WriteLine ("All work has been done"); Console.readkey ();            Let the main thread wait, otherwise "flash over"}void jobforathread (object state) {int vjobindex = (int) state; Console.WriteLine ("Job {0} Started.", Vjobindex); for (int i = 1; I <= 5; i++) {Console.Write                Line ("Running Thread {0},step {1},job {2}", Thread.CurrentThread.ManagedThreadId, I, Vjobindex);            Thread.Sleep (500); } Mautoresetevent[vjobindex].Set (); }

Operation Result:

[]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.