C # multi-thread demo

Source: Internet
Author: User

First, we will write a simple single-threaded program, that is, the main thread created by the program itself, without multithreading. create a new project and add a label named label1 to the window. We want label1 to display a number when the program is running, for example, 100; generally, label1.Text = "100" is written directly in the window loading event. In this way, label1 displays 100. The Code is as follows: (Example 1) using System; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "100" ;}}} is simple. Do you understand it ?? What, no, ah ~~~ God ~~~ Help me, please flip the book and read out the most basic and Basic Books to see the simplest and simplest examples in it (don't say I know you later, let's take a look at it. Now we need to change the program slightly and add a Button named button1. After we press button1, to display the text of lable1 from 0 to 100, we need to add the Click event of button1 and write the loop to display 0 to 100 in the click event. the Code is as follows: (Example 2) using System; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "0 ″;} Private void button#click (object sender, EventArgs e) {for (int I = 0; I <101; I ++) {label1.Text = I. toString () ;}}} run it and click "button1". The result is that 100 is displayed and 0 ~ is not displayed ~ 100 of the process, why? Haha, because your processor is too fast, you can only see the final result. So how can we see the intermediate process? (Let's talk about it later) First, use the function method to implement the above function. Write a function named run: private void run () {for (int I = 0; I <101; I ++) {label1.Text = I. toString () ;}} in this way, you can directly call the run function implementation function, instead of writing code in the event function. (This is advantageous) the entire code is as follows: (Example 3) using System; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "0 ″;} private void button#click (object sender, EventArgs e) {run (); // call the run function} private void run () {for (int I = 0; I <101; I ++) {label1.Text = I. toString () ;}}} here we need to increase the latency in the loop process. Suppose we have to wait every 1 s. The value of lable1 increases by 1. There are many methods, so we use a timer to implement latency. Add a timer named timer1 and add a statement to the tick event of timer1 to change the value of label1. (The Tick event is triggered after a specified interval.) The Code is as follows: (Example 4) using System; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {int I; // global variable I public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "0";} private void button#click (object sender, EventArgs e) {run ();} private void run () {I = 0; timer1.Interval = 1000; // set the timer1 interval timer1.Start (); // start Timer1} private void timereffectick (object sender, EventArgs e) // Tick event of timer1 {I ++; if (I> 100) {timer1.Stop ();} label1.Text = I. toString () ;}} Similarly, let's run it and check the result. It's good. We can see 0 ~ 100. Now we are going to start multithreading. Do you understand the above content? Before getting started with multithreading, let me briefly talk about defining threads. (I won't talk about other content related to multithreading. That's too much.) To use multithreading, We need to reference System. threading. threading; how to define a thread? The following statement defines a Thread private Thread thread1 named thread1. After defining a Thread similar to a defined function, it needs to be instantiated: thread1 = new Thread (new ThreadStart (run )); this statement is used to instantiate thread1 and set the run function to the thread1 entry function (I understand it in this way) after creating a thread, how can I run the thread? In fact, it is similar to starting timer1. thread1.Start (); it runs the thread thread1. Okay, you're done! Haha, don't worry. Since we have created a thread, we have to cancel the thread when closing the window. Add a FormClosing event and write the code such as the cancel thread in the event: private void form=formclosing (object sender, FormClosingEventArgs e) {if (thread1.IsAlive) // judge whether thread1 exists, you cannot undo a non-existing thread. Otherwise, an exception {thread1.Abort (); // undo thread1} is thrown. The Code is as follows: (example 5) (modified on the basis of Example 3) using System; using System. threading; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {private Thread thread1; public Form1 () {InitializeCompon Ent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "0";} private void button#click (object sender, EventArgs e) {thread1 = new Thread (new ThreadStart (run); thread1.Start () ;}private void run () {for (int I = 0; I <101; I ++) {label1.Text = I. toString () ;}} private void form=formclosing (object sender, FormClosingEventArgs e) {if (thread1.IsAlive) {thread1.Abort () ;}}} run it and press button1 An error occurred. What happened ???? Haha ~~ Check the cause of the error. It is the label1.Text = I. ToString (); statement error in the run function. That's right. The syntax is correct. Haha ~~ I will explain that the cause of the error is that the control cannot be called across threads to protect data security, while label1.Text = I. toString (); the sentence is to call the control of the main thread on the thread thread1, and it will definitely make an error !! What should we do? Use delegation. (For more information about delegation, see other materials.) I understand that thread thread1 cannot call the lable1 of the main thread. Therefore, delegate the main thread to change the value of lable1. First, let's look at an example: (rewrite from example 3) (only the main thread is not created) to create a function to set the value of lable1; private void set_lableText (string s) {label1.Text = s;} When you need to change the value of lable1, call it and pass the value to be changed. The Code is as follows: (Example 6) using System; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {label1.Text = "0 ″;} private void button#click (object sender, EventArgs e) {run (); // call the run function} private void run () {for (int I = 0; I <101; I ++) {set_lableText (I. toString () ;}} private void set_lableText (string S) {label1.Text = s ;}} implements the same functions as Example 3, but adds a function. Now let's look at the delegate. We need to delegate the main thread to call the set_lableText (string s); function to change the value of lable1. First declare a delegate: delegate void set_Text (string s); create a global delegate variable: (it should be a variable) set_Text Set_Text; // note the case sensitivity. set_Text is the delegate type, set_Text is the created delegate (of course, the name here is random). It is similar to the creation thread and needs to be instantiated: Set_Text = new set_Text (set_lableText ); // The set_lableText in the brackets is the function to be called by the delegate (that is, the set_lableText (string s) Written in Example 6). Now, the call delegate is left. How can I call the delegate? Very simple. Same as Invoke, the statement is as follows: label1.Invoke (Set_Text, new object [] {I. toString ()}); // Set_Text is the delegate of the call, and object [] is the parameter to be passed. The Code is as follows: (Example 7) using System; using System. threading; using System. windows. forms; namespace ThreadTest {public partial class Form1: Form {private Thread thread1; // defines the Thread delegate void set_Text (string s); // defines the delegate set_Text Set_Text; // define the delegate public Form1 () {InitializeComponent ();} private void Form1_Load (o Bject sender, EventArgs e) {label1.Text = "0"; Set_Text = new set_Text (set_lableText); // instantiate} private void button#click (object sender, EventArgs e) {thread1 = new Thread (new ThreadStart (run); thread1.Start ();} private void set_lableText (string s) // function called by the main Thread {label1.Text = s ;} private void run () {for (int I = 0; I <101; I ++) {label1.Invoke (Set_Text, new object [] {I. toString ()}); // call the delegate to change the value of lable1 T. Hread. sleep (1000); // thread Sleep time, in the unit of ms} private void Form1_FormClosing (object sender, FormClosingEventArgs e) {if (thread1.IsAlive) // determine whether thread1 exists, you cannot undo a non-existing thread. Otherwise, an exception {thread1.Abort (); // undo thread1 }}} is thrown. In this case, a simple multi-threaded program is completed.

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.