C # multithreading thread pool,

Source: Internet
Author: User

C # multithreading thread pool,

LineThe System. Threading. ThreadPool can be used to send work items, process asynchronous I/O, represent other threads waiting, and process timers. Basic usage:

Public void Main () {ThreadPool. queueUserWorkItem (JobForAThread); // submit a job to the thread pool} void JobForAThread (object state) // the job to be executed by the thread: The Job meeting the delegate WaitCallback {for (int I = 1; I <= 5; I ++) {Console. writeLine ("Running Thread {0}, Step {1}", Thread. currentThread. managedThreadId, I); Thread. sleep (500 );}}

After the ThreadPool. QueueUserWorkItem () method is executed, the processor automatically selects a thread in the pool to process "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 at least one idle thread exists, the thread pool will hand over the "work content" to the idle thread for processing.

3. If there are no Idle threads in the thread pool at that time, the job will be in the waiting state until there are Idle threads to process it.

 

ConnectUse the ThreadPool. GetMaxThreads () method to retrieve the number of thread pool requests that can be simultaneously active.

Int vWorkerThreads; int vCompletionPortThreads; ThreadPool. getMaxThreads (out vWorkerThreads, out vCompletionPortThreads); Console. writeLine ("Maximum number of auxiliary threads in the pool {0}, maximum number of asynchronous I/O threads in the pool {1}", vWorkerThreads, vCompletionPortThreads );

 

You can use the ThreadPool. SetMaxThreads () method to set the number of thread pool requests that can be simultaneously active.

ThreadPool. SetMaxThreads (5, 4 );

However, the number of auxiliary threads or the number of asynchronous I/O finished threads cannot be set to a bit smaller than the number of computer processors. The thread pool is easy to use, but there are some restrictions:

1. All threads in the thread pool are background threads. If all foreground threads of a process are finished, all background threads are stopped. You cannot change the thread into the pool to the foreground thread.

2. The priority or name cannot be set for the thread that enters the pool.

3. the threads in the pool can only be used for tasks with shorter time periods. If the Thread is always running, you should use the Thread class to create a Thread.

ToJobForAThread () refers to the object state parameter passed by the job, which is called:

Public void Main () {ThreadPool. queueUserWorkItem (JobForAThread, "This is a parameter passed to the work content"); // when adding a job, pass the parameter Console. readKey (); // wait for the main thread; otherwise, it will be "flashed"} void JobForAThread (object state) {Console. writeLine ("received message: {0}", (string) state); // process the passed data for (int I = 1; I <= 5; I ++) {Console. writeLine ("Running Thread {0}, Step {1}", Thread. currentThread. managedThreadId, I); Thread. sleep (500 );}}

 

 

Simple Control Operations 

IIn general, after "work" is handed over to the thread pool, it is not controlled, and the processor automatically determines when to start the execution (of course there are Idle threads ). You can use the following code to run the job after the specified time.

ManualResetEvent mManualEvent; public void Main () {mManualEvent = new ManualResetEvent (false); // instance ThreadPool. queueUserWorkItem (JobForAThread); Console. the WriteLine ("{0} task has been handed over to the thread pool, but it is not executed. ", DateTime. now. toString ("HH: mm: ss"); Thread. sleep (10000); // wait 10 s for mManualEvent. set (); // sends a signal to let the thread continue to execute the Console. readKey (); // wait for the main thread; otherwise, it will be "flashed"} void JobForAThread (object state) {mManualEvent. waitOne (); // wait for "mManualEvent. set (); "This statement is executed (sending signals) Console. writeLine ("{0} is now running the task. ", 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 (500 );}}

Running result:

After the work is handed over to the thread pool, the thread is stuck in mManualEvent during job execution. waitOne (); the subsequent code is not executed until the main thread sends a signal after 10 s. This is a "false start" control operation, which is essentially not implemented so that the specified job can start to work as desired. Here, when the ManualResetEvent object is initialized, the parameter "false" indicates that the signal is Set to "blocking state" by default, and the signal is Set to "resumable state" by code mManualEvent. Set ". On the contrary, you can set the thread to "blocked" by code mManualEvent. Reset ".

YesTo continue executing some other code.

AutoResetEvent [] mAutoResetEvent; public void Main () {mAutoResetEvent = new AutoResetEvent [] {new AutoResetEvent (false). // The default signal is blocking new AutoResetEvent (false ), new AutoResetEvent (false)}; for (int I = 0; I <3; I ++) // create 3 jobs {Thread. sleep (1000); ThreadPool. queueUserWorkItem (JobForAThread, I);} Console. writeLine ("all jobs have been added to the pool... "); WaitHandle. waitAll (mAutoResetEvent); // wait until all signals in the mAutoResetEvent change to continue, and continue the subsequent code Console. writeLine ("All work has been completed"); Console. readKey (); // wait for the main thread; otherwise, it will be "flashed"} void JobForAThread (object state) {int vJobIndex = (int) state; Console. writeLine ("Job {0} Started. ", vJobIndex); for (int I = 1; I <= 5; I ++) {Console. writeLine ("Running Thread {0}, Step {1}, Job {2}", Thread. currentThread. managedThreadId, I, vJobIndex); Thread. sleep (500);} mAutoResetEvent [vJobIndex]. set ();}

Running result:

 

[Http://www.cnblogs.com/CUIT-DX037/]

 

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.