C# Introduction to Object Oriented Programming (Asynchronous Programming & Multithreading)

Asynchronous programming

Example 1: Synchronous programming vs asynchronous threads

Compute the square of a number synchronously and asynchronously, respectively. Define two methods in order to display the effect, one of which is executed with a delay

 The encoding is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncDemo
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 同步执行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClick1_Click(object sender,EventArgs e)
        {
            this.lblCount1.Text = this.ExerTask1(10).ToString();
            this.lblCount2.Text = this.ExerTask2(10).ToString();
        }
        //[2] Define the method according to the delegate
        private int ExerTask1(int num)
        {
            System.Threading.Thread.Sleep(5000);//Delay 5 seconds to execute
            return num * num;
        }
        private int ExerTask2(int num)
        {
            return num * num;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// Asynchronous execution
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClick2_Click(object sender, EventArgs e)
        {
            //[3] Call
            CalculateDelegate asynchronously objCalculateDelegate = ExerTask1;//Create a delegate object and point to the first method
            IAsyncResult result = objCalculateDelegate.BeginInvoke(10, null, null);//Asynchronous call task
            //BeginInvoke of delegate type (<input and output variables> (parameters in delegate method), AsyncCallback callback, object asyncState) method: asynchronously called Core
            //The first parameter 10, indicating the actual parameter corresponding to the delegate
            //The second parameter callback: callback function, indicating the function that is automatically called after the asynchronous call
            //The third parameter asyncState: used to provide parameter information to the callback function
            //Return value: IAsyncResult asynchronous operation status interface, which encapsulates the parameters in asynchronous execution
            this.lblCount1.Text = "Calculating, please wait...";


            //Execute another method at the same time
            this.lblCount2.Text = this.ExerTask2(10).ToString();

            //Get the result of asynchronous execution
          
            int res = objCalculateDelegate.EndInvoke(result);
            //EndInvok() method of delegate type: With the help of IAsync interface object, continuously Query whether the asynchronous call is over
            //The method knows all the parameters of the method of the asynchronous call, so after the asynchronous call is completed, the result of the asynchronous call is taken as the return value
            this.lblCount1.Text = res.ToString();


        }
    }
    //[ 1] Declare the delegate
    public delegate int CalculateDelegate(int num);
}
Example 2: Demonstrate the application of the asynchronous callback function, the console delays displaying the calculated value of the square of the number 10 times

Results of the:

 

 

The encoding is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncDemo2
{
    /// <summary>
    /// Demonstrate the application of the asynchronous callback function, the console delays displaying the digital square calculation value 10 times
    /// </summary>
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent() ;
            //[3] Initialize the delegate variable
            this.objCal = new CalculateDelegate(Calculate);
        }
        //[2] Define the method according to the delegate
        private int Calculate(int num,int ms)
        {
            System.Threading.Thread.Sleep(ms);
            return num * num;
        }
        //[3]Create a delegate object

        CalculateDelegate objCal = null;
        /// <summary>
        /// Asynchronously call the callback function to perform multiple tasks at the same time
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAsyncCallback_Click( object sender, EventArgs e)
        {
            //[4]Asynchronous call
            for(int i = 1; i < 11; i++)
            {
                //Start asynchronous execution and encapsulate the callback function
               objCal.BeginInvoke(10 * i, 1000 * i,CalCallback, i);
                //The last parameter i is assigned to the field AsyncState of the callback function, which is of type object
            }

        }
        //[5] Write the callback function
        private void CalCallback(IAsyncResult result)
        {
            int res = objCal.EndInvoke(result);
            Console.WriteLine ("The {0}th output result is: {1}", result.AsyncState.ToString(), res.ToString());
        }
    }
    //[1] declare the delegate
    public delegate int CalculateDelegate(int num, int ms);
 
}

  Summary of asynchronous programming:
    1. Asynchronous programming is a programming method based on delegation.
    2. Each method called asynchronously is executed in a separate thread. Therefore, it is essentially a multi-threaded program, and it can also be said to be a simplified multi-threaded technology
    . 3. It is more suitable to run the time-consuming "Simple Task" in the background, and requires that the tasks be independent, and the tasks are not required. 4. If background tasks must be
    executed in a specific order, or access specific shared resources, asynchronous programming is not suitable, and multi-threaded development techniques should be selected

 

Multithreading

Example 3: Display the output of two threads at the same time in the console

operation result:

 

 code show as below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace TheadTest
{
    /*
     *Process: A running program is a process, and the operating system allocates various resources (memory...) according to the process
     *Thread: The operating system divides a process into multiple Threads, and allocate CPU execution time according to threads
     * Thread characteristics: In a computer with multiple CPUs, parallel execution is possible. 1CPU 12 thread rotation false multi-threading
     *Thread class: Represents a managed thread, each Thead object represents a managed thread, and each managed thread corresponds to a function.
     *ProcessThread type: Consistent with OS native thread
     *TheadStart() method definition: public delegate void ThreadStart();
    */
    public partial class FrmThead : Form
    {
        public FrmThead()
        {
            InitializeComponent();
        }

        //Task 1: loop out a result
        private void btnThead1_Click(object sender, EventArgs e)
        {
            Thread objThread1 = new Thread(delegate ()
              {
                  int a = 0;
                  for(int i = 1; i <= 20; i++)
                  {
                      Console.WriteLine((a+i)+" ");
                      Thread.Sleep(500);
                  }
              });//Anonymous method defines delegate method
            objThread1.IsBackground = true;/ /Defined as background thread
            objThread1.Start();
        }
        //Task 2
        private void btnThead2_Click(object sender, EventArgs e)
        {
            Thread objThread2 = new Thread(()=>
            {
                int a = 0;
                for (int i = 1; i <= 50; i++)
                {
                    Console.WriteLine("--- --------a"+i+"------------");
                    Thread.Sleep(100);
                }
            });//Lamada defines the delegate method
            objThread2.IsBackground = true ;//Defined as background thread
            objThread2.Start();

        }
    }
}
Example 4: Cross-thread visual control. The controls of the two threads cannot be directly accessed and need to use the Invoke() method

code show as below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CrossThreadVistControl
{
    public partial class FrmCrossThreadVist : Form
    {
        public FrmCrossThreadVist()
        {
            InitializeComponent();
        }

        private void btnThread1_Click(object sender, EventArgs e)
        {
            Thread objthread1 = new Thread(() =>
              {
                  int a = 0;
                  for (int i = 0; i <= 100; i++)
                  {
                      a += i;
                      if (this.lblCount1.InvokeRequired)//Determine whether to call the Invoke method
                      {
                          //Invoke() method first The parameter is a delegate whose return value is void, and the second parameter is the delegate's corresponding method passing parameters
                          //Action is a delegate collection variable with one parameter but no return value
                          this.lblCount1.Invoke(new Action<string>(s => { this.lblCount1.Text = s; }), a.ToString());
                      }
                      Thread.Sleep(200);
                  }

              });
            objthread1.IsBackground = true;
            objthread1.Start();
        }

        private void btnThread2_Click(object sender, EventArgs e)
        {
            Thread objthread2 = new Thread(() =>
            {
                int a = 0;
                for (int i = 0; i <= 100; i++)
                {
                    a += i;
                    if (this.lblCount2.InvokeRequired)//判断是否调用Invoke方法
                    {
                        this.lblCount2.Invoke(new Action<string>(s => { this.lblCount2.Text = s; }), a.ToString());
                    }
                    Thread.Sleep(200);
                }

            });
            objthread2.IsBackground = true;
            objthread2.Start();
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688168&siteId=291194637