实现的功能是
按button2之后,label2会每100毫秒显示一次数字,数字从0到99。(委托方式实现)
button3之后,模拟耗时操作5秒后label3显示为当前时间。(BackgroundWorker方式实现)
⒃?、2执行的时候,按button1可以将label1的内容改为textbox1的内容。(此处为主线程控制,用于显示多线程未死锁主线程)
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
private delegate void SetState(int x);//代理
public Form1()
{
InitializeComponent();
Thread.CurrentThread.Name = "Main";//主线程命名
Console.WriteLine(Thread.CurrentThread.Name);
}
private void TempFunction() //中转函数,用来连续多次调用目标函数并模拟延时
{
for (int i = 0; i < 100;i++ )
{
ThreadFunction(i);
Thread.Sleep(100);
}
}
private void ThreadFunction(int x) //实际控件操作函数
{
if (label2.InvokeRequired) //用委托来操作
{
SetState ss = new SetState(ThreadFunction);
Invoke(ss,new object[]{x});
Console.WriteLine(Thread.CurrentThread.Name);
}
else //普通方式操作
{
label2.Text = x.ToString();
label2.Update();
Console.WriteLine(Thread.CurrentThread.Name);
}
}
private void button1_Click(object sender, EventArgs e) //主线程的按钮操作,用来显示区别所在
{
label1.Text = textBox1.Text;
}
private void button2_Click(object sender, EventArgs e) //按下按钮后开始多线程操作
{
Thread th1 = new Thread(new ThreadStart(TempFunction));
th1.IsBackground = true;
th1.Name = "kidfruit";
th1.Start();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //使用BackgroundWorker控件
{
Thread.Sleep(5000); //模拟操作延时
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) //BackgroundWorker耗时操作结束后
{
label3.Text = DateTime.Now.ToLongTimeString();
}
private void button3_Click(object sender, EventArgs e) //开始BackgroundWorker的耗时操作
{
backgroundWorker1.RunWorkerAsync();
}
}
}
本文作者:网友 来源:中国IT实验室
CIO之家 www.ciozj.com 微信公众号:imciow