C#如何进行多线程编程

由于多线程编程非常复杂,这个小例子只能算是一个入门线的知识点吧

首先建一个应用程序项目,命名为ThreadExample,在窗体上放一个文本框(textBox1) ,一个标签(lblResult),再放两个按钮,分别命名为btnStart、btnStop。

窗体代码:

namespace ThreadExample
{
    partial 
class ThreadExample
    {
        
/**//// <summary>
        
/// Required designer variable.
        
/// </summary>
        private System.ComponentModel.IContainer components = null;

        
/**//// <summary>
        
/// Clean up any resources being used.
        
/// </summary>
        
/// <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

        
/**//// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>
        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(1438);
            
this.btnStart.Name = "btnStart";
            
this.btnStart.Size = new System.Drawing.Size(7523);
            
this.btnStart.TabIndex = 0;
            
this.btnStart.Text = "启动";
            
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            
// 
            
// btnStop
            
// 
            this.btnStop.Location = new System.Drawing.Point(1468);
            
this.btnStop.Name = "btnStop";
            
this.btnStop.Size = new System.Drawing.Size(7523);
            
this.btnStop.TabIndex = 1;
            
this.btnStop.Text = "停止";
            
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(1497);
            
this.button1.Name = "button1";
            
this.button1.Size = new System.Drawing.Size(7523);
            
this.button1.TabIndex = 3;
            
this.button1.Text = "关闭";
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(1411);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(7521);
            
this.textBox1.TabIndex = 4;
            
this.textBox1.Text = "200";
            
// 
            
// lblResult
            
// 
            this.lblResult.AutoSize = true;
            
this.lblResult.Location = new System.Drawing.Point(12139);
            
this.lblResult.Name = "lblResult";
            
this.lblResult.Size = new System.Drawing.Size(2312);
            
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(104164);
            
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;

namespace ThreadExample
{
    
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,点击开始按钮,标签为动态增长,点击停止可以暫停程序的执行。


本文转自yonghu86 51CTO博客,原文链接:http://blog.51cto.com/yonghu/1321402,如需转载请自行联系原作者
上一篇:C#访问修饰符总结[转]


下一篇:Android平台SQLite快速入门实践