C # thread pool usage

Source: Internet
Author: User

Translation: http://www.dotnetperls.com/threadpool

In the C # programming language, you can use a thread pool to process jobs in parallel. When a thread is forced and a progress bar is updated, the threadpool class of the built-in architecture is used to use a multi-core structure for batch processing, here we will look at some information about the C # programming language from the system. example of threadpool usage for threading.

Introduction

. NET Framework provides the system. Threading space containing the threadpool class. This is a directly accessible static class, which is essential for the thread pool. It is the implementation of the public "Thread Pool" design style. It is useful for running many different tasks in the background. There are better options for a single background line.

The maximum number of threads. This is completely unknown. The main point of threadpool in. NET is that it manages threads in the internal thread pool. Multi-core machines will have more threads than previous machines. Microsoft states that "the thread pool usually has the maximum number of threads. If all threads are busy, the added tasks are placed in the queue until they can be served, can be used as an available thread."

Usage location

The thread pool type can be used in servers and batch processing applications. The thread pool has a cheaper internal logic for obtaining threads, when necessary, these threads have been formed and just "connected", so the thread pool style code is used on the server.

Msdn states: "The thread pool is often used in server applications. Every new requirement is allocated to a thread in a thread pool, so that this requirement can be executed asynchronously, it does not impede the processing of the main thread or delay subsequent requests."

Msdn reference

Threadpool vs backgroundworker

If you are using a Windows form, you would rather use backgroundworker to deal with simpler thread requirements. backgroundworker is doing well in terms of network access and other simple things. But for multi-processor batch processing, you need threadpool.

Backgroundworker tutorial

When your program needs batch processing, consider the thread pool

When your program generates many (more than three) threads, consider the thread pool

When your program uses a Windows form, consider background execution.

The thread should also consider how to use the fine energy saving of the thread to help find the best code. The following compares the thread condition and the class that is the best.

You need an additional thread for background execution.

You have many short-term threads using the thread pool

Requirement

Threads are important, but they are not important for most applications that don't take a long time to execute and only do one thing. Threads are not very important for applications whose interface availability is not very important. Avoid using threads whenever possible (for example, progress bars are not very important applications ).

Connection Method

You can use the queueuserworkitem connection method (methods) to connect to the thread pool. To run the method on a thread, you must connect it to queueuserworkitem. How to implement it? Waitcallback is required. In msdn, waitcallback is described as the delegate callback method to be called when the thread pool is executed. It is the delegate of the parameter for callback.

Waitcallback

You only need to specify the "New waitcallback" statement as the first parameter of threadpool. queueuserworkitem to use waitcallback. This method takes effect without any other code.

Example of using waitcallback [C #]

Void example () {// connect the processfile Method to the thread pool. // Note: 'A' is a threadpool object as a parameter. queueuserworkitem (New waitcallback (processfile), a);} private void processfile (Object A) {// I am connected to the thread pool through waitcallback .}

Parameters

We can use parameters by defining a specific class and placing some important values in the class. Then, if the method receives the object, it can pass multiple parameters to the method through the object. The following is an early example.

Example of using the queueuserworkitem parameter [C #]

// Class threadinfo {Public String filename {Get; set;} public int selectedindex {Get; Set ;}} class example {public example () {// declare a new parameter object threadinfo = new threadinfo (); threadinfo. filename = "file.txt"; threadinfo. selectedindex = 3; // send the custom object to the threadpool of the thread method. queueuserworkitem (New waitcallback (processfile), threadinfo);} private void processfile (Object A) {threadinfo = A as threadinfo; string filename = threadinfo. filename; int Index = thread. selectedindex ;}}

What happened? We send two values to this thread-based processfile method. It needs to know the file name and select the index, and we have sent all the parameters to this object.

Progress bar

You can use the progress bar and set progressbar1.value, progressbar1.minimum, and progressbar1.maximum by adding a Windows Form Control to your form program from the Toolbox panel on the right of the designer. Progressbar1.value is the center of the minimum and maximum values. The following code initializes the progress bar:

Example of setting progress bars [C #]

// Set the length of the progress bar. // here we have 6 units to complete, so 6 is the maximum value. // The minimum value is usually 0 progressbar1. Maximum = 6; // or other numbers progressbar1.minimum = 0;

Progress bar position the color part in your progress bar is the percentage of the current value and the maximum value. Therefore, if the maximum value is 6, and the value is 3, it means that half is done.

Progressbar example (Windows Forms)

Call invoke in progress bar)

Let's see how to use the invoke method in the progress bar instance. Unfortunately, you cannot access Windows controls in the guides, because the UI threads are separated and must use the delegate and invoke to the progress bar.

Example of requesting invoke (CALL) [C #]

Public partial class mainwindow: FORM {// This is the delegate Public Delegate void bardelegate () that runs to update entries in the UI thread; // The constructor of the form (generated by Visual Studio itself) public mainwindow () {initializecomponent () ;}// when the button is pressed, start a new thread private void button_click (Object sender, eventargs e) {// set the length of the progress bar. progressbar1.maximum = 6; progressbar1.minimum = 0; // pass these values to the thread. threadinfo = new threadinfo (); threadinfo. filename = "file.txt"; threadinfo. selectedindex = 3; threadpool. queueuserworkitem (New waitcallback (processfile), threadinfo);} // Private void processfile (Object A) running on the background thread {// (omitted) // use 'A' to do important things. // tell the UI that we have finished it. try {// call the delegate in the form. this. invoke (New bardelegate (updatebar);} catch {// when some problems occur, we can restore the program to normal} // update the progress bar. private void updatebar () {progressbar1.value ++; If (progressbar1.value = progressbar1.maximum) {// The progress bar is full .}}}

At the beginning of the code above the delegate syntax, you can see the delegate that declares updatebar. It tells Visual Studio and C # How to use this method as an object.

More work is required. The above program demonstrates how to set the maximum and minimum values of the progress bar, and how to "INVOKE" The delegate method after the work is completed to increase the progress bar size.

Threads in the debugger

The following shows how to view threads in the Visual Studio debugger. Once you have a running program, you can take these measures to visualize your thread. First, open your thread application in debug mode. Once your application runs in the debugger, tell it to do its work and run these threads, and run the debugger through the Green Arrow, when the thread is running, click "pause" in the toolbar.

Next debugging> WINDOW> thread. This menu item opens a similar window where you can see how many threads are running in the thread pool.

 

There are 10 threads in the four worker threads, but only four worker threads are allocated to mainwindow. processfile in the program.

Constraint auxiliary thread

If you have a dual-core or quad-core system, you will consider up to two four very laborious threads. We can keep a _ threadcount field in the running thread and track its value. To use this thread to count fields, you will need to use a lock in the C # language to avoid reading and writing errors of this field. The lock protects your thread from being changed by other threads.

Example of counting threads [C #]

// Lock this object. readonly object _ countlock = new object (); Private void processfile (Object argument) {// restrict the number of auxiliary threads while (true) {lock (_ countlock) {If (_ threadcount <4) {// start the processing_threadcount ++; break ;}} thread. sleep (50);} // do work ...}

We can see what the code is asynchronously executed. It works only when there are fewer than four other auxiliary threads. This is good for a quad-core machine. Please refer to the article describing more context of lock Declaration

Lock statement

Control thread counters

You can use setminthreads on the threadpool to improve throughput and performance in bursts of events. The following are materials about the optimum minimum number of threads that can be used.

Threadpool. setminthreads Method

Summary

We learned how to use the thread pool in the C # program to effectively manage multiple threads, which can be impressive and difficult to implement in the progress bar and user interface of the Windows form application. However, the thread brings a lot of complexity and leads to vulnerabilities. The thread pool is a useful simplification, but it is still difficult.

Thread Summary

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.