C # multithreading (1 ),

Source: Internet
Author: User

C # multithreading (1 ),

Overview:

1. process: it is the basis of the operating system structure; it is a program in progress; an instance of a program running in the computer; it can be allocated to an entity executed by the processor; the execution in a single order shows the activity units described by the current status and a group of related system resources.

2. Thread: A thread is a single sequential control process in a program. Is the smallest unit of the program execution flow. In addition, a thread is an entity in a process and is the basic unit for independent scheduling and distribution by the system. A thread itself does not own system resources, but only has a few resources that are essential for running, however, it can share all resources of a process with other threads of the same process. One thread can create and withdraw another thread, and multiple threads in the same process can execute concurrently. Due to mutual constraints between threads, the threads are intermittently running. The thread also has three basic states: Ready, blocked, and running. Each program has at least one thread. If the program has only one thread, it is the program itself.

3. multithreading: multiple threads are run in a single program to complete different tasks.

Summary:In fact, it is easier to understand processes and threads. For example, we can understand processes as an operating company. However, every employee of a company can be called a thread. Each company must have at least one employee. The more employees you have, the better the company's operation speed if your management is reasonable. Here, the official taste is just a little bit. Cpu is idle most of the time, wasting cpu resources. multithreading allows a program to "simultaneously" handle multiple tasks and improve efficiency.

Single-thread problem demonstration

Create a WinForm application. If you click the button before the prompt box is displayed, the form cannot be dragged.

Private void button#click (object sender, EventArgs e) {for (int I = 0; I <10000000000; I ++) {I ++ = 1;} MessageBox. show ("you can drag after it appears, prompting that the form cannot be dragged before it appears"); // The form will not respond}

Cause: when running this application, the form application comes with a thread called UI, which is responsible for moving the size of the form interface. If you click the button, the thread will process the cyclic computation and discard other operations. Therefore, no response is returned when you drag the form. This is a single thread problem.

Solution: use multithreading to create a thread. Put the computing code into the thread we write, and the UI thread can continue to respond to the interface.

Thread Creation

Thread implementation: the thread must execute a piece of code, so to generate a thread, you must first write a method for the thread, the code in this method, is the code to be executed in the thread. However, when the thread is started, the method is called by Delegate. When a thread starts, the delegate that calls the passed delegate executes the corresponding method to implement the thread execution method.

// Create thread private void button#click (object sender, EventArgs e) {// ThreadStart is a delegate with no parameters and no return values. ThreadStart ts = new ThreadStart (js); // initialize a new instance of the Thread, and assign the delegate ts as the parameter to the initial value through the constructor. Thread td = new Thread (ts); // you need to introduce the System. Threading namespace // run the function to be executed by the delegate td. Start () ;}// created Thread. Void js () {for (int I = 0; I <1000000000; I ++) {I + = 1;} MessageBox. show ("the front and back forms can be dragged ");}

Writing this computation into a self-written thread solves the interface no response defect in a single thread.

Summary:Four steps for creating a thread: 1. Compile the method for thread request execution. 2. the reference System. Threading name is null. 3. instantiate the Thread class and input a delegate pointing to the method to be run by the Thread. 4. Call the Start () method to mark the thread as a running state, but the execution time is determined by the cpu.

Method re-import (multiple threads execute one method)

Because the thread can share all the resources of the process with other threads of the same process.

Therefore, multiple threads execute a method at the same time. However, if this problem is not processed, a problem may occur. The threads compete for resources successively, leading to disordered data computing results.

 

Public partial class method re-import: Form {public method re-import () {InitializeComponent (); // set this attribute of the TextBox class because the ui thread is enabled, // Microsoft settings detection does not allow other threads to access the data of the ui thread. Here, we disable the detection and allow other threads to access the data of the ui thread. // If this parameter is not set to False, an error is returned. TextBox. checkforillegalcrossthreadcils = false;} private void button#click (object sender, EventArgs e) {textBox1.Text = "0"; // enable the first thread, calculate ThreadStart ts = new ThreadStart (js), Thread td = new Thread (ts), and td. start (); // Start the second Thread and calculate ThreadStart ts1 = new ThreadStart (js); Thread td1 = new Thread (ts1); td1.Start ();} // The method that multiple threads need to re-import. Void js () {int a = Convert. toInt32 (textBox1.Text); for (int I = 0; I <2000; I ++) {a ++; textBox1.Text =. toString (); // if it is True, an error is returned: The Inter-thread operation is invalid: access it from a thread that is not creating the control "textBox1. }}}

 

Error: After you click the button, the data in TextBox1 is 2000 + or 2000. If the data you see is always 2000, it indicates that your computer's cpu is cool. In this case, if you want to see that it is not 2000, you can try it multiple times. If it doesn't work, assign TextBox1 0 in the code, and set the default value of textBox1 to 0 in the interface.

Cause of error: the two processes calculate this method at the same time. Unrelated disturbance should be that the calculation result of each thread is 2000, but the output here is beyond the limit because the first two threads calculate at the same time, it is not to start computing at the same time, but to determine which one starts first and which one starts later based on the cpu. Although there is not much time difference between them, the data that has been computed first will be used later, this will lead to computing disorder.

Solution: a simple solution to this problem is to lock the method, which means that after the first thread has used the resource, the second thread will use the resource again. Form a queuing effect.

The method is locked below.

 

 

// The method that multiple threads need to re-import. Lock it here. Void js () {lock (this) {int a = Convert. toInt32 (textBox1.Text); for (int I = 0; I <2000; I ++) {a ++; textBox1.Text =. toString ();}}}

After locking a method, the thread can use resources one after the other to avoid unexpected results. The first thread is calculated as 2000, and the second thread is calculated as starting from 2000, the result is 4000.

Summary:Multiple Threads can run at the same time, improving the cpu efficiency. Here, they do not start at the same time, but end at the same time. Their start is determined by the cpu, and the time difference is not big, however, there may be unpredictable calculation errors. Pay attention to the method reconnection problem caused by the above example.

 Foreground thread background thread

The. Net public language can distinguish two different types of threads: foreground thread and background thread. The difference between the two is that the application can exit only after running all the foreground threads. For background threads, the application can exit without considering whether it has been completed, all background threads automatically end when the application exits.

Problem: the window is closed and the message box is displayed.

Private void button#click (object sender, EventArgs e) {// start a Thread and calculate ThreadStart ts2 = new ThreadStart (js) for the js method; Thread td2 = new Thread (ts2 ); td2.Start ();} void js () {for (int I = 0; I <2000000000; I ++) // if the result is not displayed, add 0 {I ++;} MessageBox next to 2. show ("I still want to come out after closing the window! ");}

Cause: the. Net environment uses Thread to create a Thread. The default Thread is the foreground Thread. That is, the thread attribute IsBackground = false, and the foreground thread does not close the application as long as one is running. Therefore, the application is closed only when the message box is displayed.

Solution: Set td2.IsBackground = true in the code;

 Thread execution method with Parameters

 

// Create a thread private void button#click (object sender, EventArgs e) that executes the method with parameters) {// ParameterizedThreadStart this is a delegate ParameterizedThreadStart pts = new ParameterizedThreadStart (SayHello); Thread td2 = new Thread (pts); td2.Start ("James "); // enter the parameter value here first} void SayHello (object name) {MessageBox. show ("hello," + name. toString () + "! ");}

Thread execution method with multiple parameters

In fact, it is still a method with a parameter, but it only takes advantage of the parameter type as the object. Here, the type is passed to the list type, which looks like multiple parameters.

// Create a private void button#click (object sender, EventArgs e) {List <string> list = new List <string> {"Zhang San ", "Li Si", "Wang Wu"}; // ParameterizedThreadStart this is a parameter-type object delegate ParameterizedThreadStart pts = new ParameterizedThreadStart (SayHello); Thread td2 = new Thread (pts ); td2.Start (list); // enter the parameter value here first} void SayHello (object list) {List <string> lt = list as List <string>; for (int I = 0; I <lt. C Ount; I ++) {MessageBox. Show ("hello," + lt [I]. ToString () + "! ");}}

Conclusion: I believe we should have a preliminary understanding of multithreading, so I will not talk about it.

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.