. NET WinForm programming Q & amp; A series (1) -- Multithreading

Source: Internet
Author: User

Preface when there are a large number. after the NET programmers enter this field, we can quickly develop a lot of applications using the "instant gain" mechanism. However, as we go deep into this field, we will find that, UI-based design often fails to develop ideal system prototypes ~ A 3-year-old. NET programmer still cannot understand many concepts, such as multithreading, reflection, and ** mechanisms, as well as myself. Therefore, ". NET WinForm programming Q & A series" is based on my understanding. The entire series will include the following content: [background] focuses on issues in WinForm programming and related obscure concepts; [concepts] introduction to these problems and concepts in textbooks or Baidu encyclopedia, I guess most programmers do not want to accept this method. [requirement] I propose a system instance based on these problems and concepts, it is also hoped that this instance can be used to solve a number of problems raised by the background, and let everyone sort out the concept. [practice] describes in detail the implementation process of the instance, of course, for the instance, there will be a lot of solutions. The practical process proposed in this article is only one of them. [Remarks] You are welcome to give your comments. Background how to understand and apply multithreading? Concept 1. multithreading is used to synchronize multiple tasks, not to improve the running efficiency, but to improve the resource usage efficiency to improve the system efficiency. A thread is implemented when multiple tasks need to be completed at the same time. 2. A thread can be used to put tasks in a program that occupies a long time into the background for processing; 3. In essence and structure ,. NET is a multi-threaded environment. There are two main multithreading methods. NET advocate: Use ThreadStart to start your own processes directly (use ThreadPool. queueUserWorkItem) or indirect (such as Stream. beginRead or BeginInvoke) use the ThreadPool class. In general, you can "manually" Create a New thread for long-running tasks. In addition, for Short-running tasks, especially those that often need to be started, the process pool is a good choice. The process pool can run multiple tasks at the same time and use framework classes. When resources are in short supply and need to be synchronized, it can restrict only one thread to access resources at a certain time point. This situation can be considered as implementing a lock mechanism for the thread. The base class of the thread is System. Threading. All threads are managed through CLI. The required control content is changed regularly. Every 1 second, the text control displays a random number (0,100), and the progress bar is displayed. As shown in. Practice 1. Based on the system requirements mentioned in the requirement, junior programmers can quickly write the solution as follows: [csharp] private void button#click (object sender, EventArgs e) {while (true) {Random rd = new Random (); int num = rd. next (0,100); this. textBox1.Text = num. toString (); Thread. sleep (1000);} 2. After running, the interface cannot be moved. Therefore, you need to use the counter to implement the function, as shown in [csharp] private void button#click (object sender, EventArgs e) {this. timer1.Enabled = true;} private void timerreceivtick (object sender, EventArgs e) {Random rd = new Random (); int num = rd. next (0,100); this. textBox1.Text = num. toString (); this. progressBar1.Value = num; Thread. sleep (1000);} 3. After F5, we found that the system is operating normally. This is one of the solutions, but this article mainly introduces multithreading, so we should consider other steps. 4. To use a multi-threaded UI control, you must use a delegate. Call the control's Invoke method (the Invoke method parameter is a delegate type parameter ). The procedure is as follows: 1. Declare the delegate. [Csharp] /// <summary> /// 1. declare the delegate /// </summary> /// <param name = "num"> </param> delegate void RefreshData (int num); delegate void AutoRefresh (); 2. declare the delegate processing function (determine whether the main thread controls the UI control or the Invoke (multi-thread) controls the UI control ). [Csharp] /// <summary> /// 2. declare the delegate handler function refreshTextBox // </summary> /// <param name = "num"> </param> public void refreshTextBox (int num) {if (this. textBox1.InvokeRequired) {RefreshData rd = new RefreshData (refreshTextBox); if (this. textBox1.IsHandleCreated) {this. textBox1.Invoke (rd, num) ;}} else {this. textBox1.Text = num. toString () ;}/// <summary> // 2. declare the delegate handler function Display /// </summary> /// <par Am name = "num"> </param> public void Display (int num) {if (this. progressBar1.InvokeRequired) {RefreshData rd = new RefreshData (Display); if (this. progressBar1.IsHandleCreated) {this. progressBar1.Invoke (rd, num) ;}} else {this. progressBar1.Value = num ;}} 3. declare a thread instance and pass the thread function delegate to ThreadStart (). [Csharp] // 3. Declare a Thread instance Thread refreshThread = new Thread (new ThreadStart (ar); 4. Enable this Thread. [Csharp] // 4. enable refreshThread. start (); 5. define the thread function. To control the UI control, call the delegate processing function in step 1. He will use Invoke for his own judgment. 6. define the function [csharp] to be called by Invoke /// <summary> // 6. define the function to be called by Invoke // </summary> private void AddAuto () {while (true) {Random rd = new Random (); int num = rd. next (0,100); refreshTextBox (num); Display (num) ;}} complete set of remarks code: [csharp] using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. threading; namespace MulControlOp {public partial class Form1: Form {// <summary> // 1. declare the delegate /// </summary> /// <param name = "num"> </param> delegate void RefreshData (int num); delegate void AutoRefresh (); public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {} private void button#click (object sender, EventArgs e) {AutoRefresh ar = new AutoRefresh (AddAuto); // 3. declare a Thread instance Thread refreshThread = new Thread (new ThreadStart (ar); // 4. enable refreshThread. start ();} // <summary> // 6. define the function to be called by Invoke // </summary> private void AddAuto () {while (true) {Random rd = new Random (); int num = rd. next (0,100); refreshTextBox (num); Display (num) ;}/// <summary> // 2. declare the delegate handler function refreshTextBox // </summary> /// <param name = "num"> </param> public void refreshTextBox (int num) {if (this. textBox1.InvokeRequired) {RefreshData rd = new RefreshData (refreshTextBox); if (this. textBox1.IsHandleCreated) {this. textBox1.Invoke (rd, num) ;}} else {this. textBox1.Text = num. toString () ;}/// <summary> // 2. declare the delegate handler function Display // </summary> // <param name = "num"> </param> public void Display (int num) {if (this. progressBar1.InvokeRequired) {RefreshData rd = new RefreshData (Display); if (this. progressBar1.IsHandleCreated) {this. progressBar1.Invoke (rd, num) ;}} else {this. progressBar1.Value = num ;}} private void form=formclosed (object sender, FormClosedEventArgs e) {Application. exit ();} private void form=formclosing (object sender, FormClosingEventArgs e) {Application. exitThread ();}}}

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.