111,098
社区成员




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 ThreadExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//声明一个线程
private Thread timerThread;
public void AddData()
{
//显示lable的值
this.label1.Text = "正在执行脚本1...";
//执行脚本1代码
//......
//
Thread.Sleep(500);
//执行脚本2代码
//......
//
this.label1.Text = "正在执行脚本2...";
//执行脚本3代码
//......
//
Thread.Sleep(500);
this.label1.Text = "正在执行脚本3...";
}
//更新线程
public void UpdataThread()
{
try
{
//在对控件的调用方法进行调用时,或需要一个简单委托又不想自己定义时可以使用该委托。
MethodInvoker mi = new MethodInvoker(this.AddData);
//在创建控件的基础句柄所在线程上异步执行指定的委托
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 button1_Click(object sender, EventArgs e)
{
ShowProgressStatus();
}
//停止线程
private void button2_Click(object sender, EventArgs e)
{
StopProgressStatus();
}
private void ShowProgressStatus()
{
//调用线程启动函数
this.label1.Visible = true;
this.pictureBox1.Visible = true;
this.StartThread();
}
private void StopProgressStatus()
{
//调用线程停止函数
this.pictureBox1.Visible = false;
this.label1.Visible = false;
this.StopThread();
}
}
}