天天看點

C#如何進行多線程程式設計

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chinahuyong/article/details/4290888

C#如何進行多線程程式設計

由于多線程程式設計非常複雜,這個小例子隻能算是一個入門線的知識點吧

首先建一個應用程式項目,命名為ThreadExample,在窗體上放一個文本框(textBox1) ,一個标簽(lblResult),再放兩個按鈕,分别命名為btnStart、btnStop。

窗體代碼:

namespace ThreadExample

{

    partial class ThreadExample

    {

        /**//// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;

        /// Clean up any resources being used.

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

        Windows Form Designer generated code#region Windows Form Designer generated code

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        private void InitializeComponent()

            this.btnStart = new System.Windows.Forms.Button();

            this.btnStop = new System.Windows.Forms.Button();

            this.button1 = new System.Windows.Forms.Button();

            this.textBox1 = new System.Windows.Forms.TextBox();

            this.lblResult = new System.Windows.Forms.Label();

            this.SuspendLayout();

            // 

            // btnStart

            this.btnStart.Location = new System.Drawing.Point(14, 38);

            this.btnStart.Name = "btnStart";

            this.btnStart.Size = new System.Drawing.Size(75, 23);

            this.btnStart.TabIndex = 0;

            this.btnStart.Text = "啟動";

            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);

            // btnStop

            this.btnStop.Location = new System.Drawing.Point(14, 68);

            this.btnStop.Name = "btnStop";

            this.btnStop.Size = new System.Drawing.Size(75, 23);

            this.btnStop.TabIndex = 1;

            this.btnStop.Text = "停止";

            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);

            // button1

            this.button1.Location = new System.Drawing.Point(14, 97);

            this.button1.Name = "button1";

            this.button1.Size = new System.Drawing.Size(75, 23);

            this.button1.TabIndex = 3;

            this.button1.Text = "關閉";

            this.button1.Click += new System.EventHandler(this.button1_Click);

            // textBox1

            this.textBox1.Location = new System.Drawing.Point(14, 11);

            this.textBox1.Name = "textBox1";

            this.textBox1.Size = new System.Drawing.Size(75, 21);

            this.textBox1.TabIndex = 4;

            this.textBox1.Text = "200";

            // lblResult

            this.lblResult.AutoSize = true;

            this.lblResult.Location = new System.Drawing.Point(12, 139);

            this.lblResult.Name = "lblResult";

            this.lblResult.Size = new System.Drawing.Size(23, 12);

            this.lblResult.TabIndex = 5;

            this.lblResult.Text = "0/0";

            // ThreadExample

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(104, 164);

            this.Controls.Add(this.lblResult);

            this.Controls.Add(this.textBox1);

            this.Controls.Add(this.button1);

            this.Controls.Add(this.btnStop);

            this.Controls.Add(this.btnStart);

            this.Name = "ThreadExample";

            this.Text = "Form1";

            this.ResumeLayout(false);

            this.PerformLayout();

        #endregion

        private System.Windows.Forms.Button btnStart;

        private System.Windows.Forms.Button btnStop;

        private System.Windows.Forms.Button button1;

        private System.Windows.Forms.TextBox textBox1;

        private System.Windows.Forms.Label lblResult;

    }

}

程式代碼:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

    public partial class ThreadExample : Form

        //聲明一個線程

        private Thread timerThread;

        //聲明一個變量,用來存儲label值

        int count, i = 0;

        public ThreadExample()

            InitializeComponent();

        //把label的值加1;

        public void AddData()

            //顯示lable的值

            if (i == count)

                i = 0;

            this.lblResult.Text = i.ToString() + "/" + count.ToString();

            i++;

        //更新線程

        public void UpdataThread()

            try

                //在對控件的調用方法進行調用時,或需要一個簡單委托又不想自己定義時可以使用該委托。

                MethodInvoker mi = new MethodInvoker(this.AddData);

                while (true)

                {

                    //在建立控件的基礎句柄所線上程上異步執行指定的委托

                    this.BeginInvoke(mi);

                    Thread.Sleep(50);

                }

            catch (ThreadInterruptedException)

                //針對具體問題定制異常抛出顯示

            finally

                //做一些處理

        //啟動線程

        public void StartThread()

            StopThread();

            timerThread = new Thread(new ThreadStart(UpdataThread));

            //擷取或設定一個值,該值訓示某個線程是否為背景線程。

            timerThread.IsBackground = true;

            timerThread.Start();

        //停止線程

        public void StopThread()

            if (timerThread != null)

                //中斷線程

                timerThread.Interrupt();

                timerThread = null;

        //啟動線程,顯示結果

        private void btnStart_Click(object sender, EventArgs e)

            //調用線程啟動函數

            count = int.Parse(textBox1.Text);

            this.StartThread();

        private void btnStop_Click(object sender, EventArgs e)

            //調用線程停止函數

            this.StopThread();

        }       

編譯後,運作,在文本框中輸入200,點選開始按鈕,标簽為動态增長,點選停止可以暫停程式的執行。

繼續閱讀