实现的功能是
按button之后label会每毫秒显示一次数字数字从到(委托方式实现)
按button之后模拟耗时操作秒后label显示为当前时间(BackgroundWorker方式实现)
在执行的时候按button可以将label的内容改为textbox的内容(此处为主线程控制用于显示多线程未死锁主线程)
using System;
using SystemCollectionsGeneric;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemLinq;
using SystemText;
using SystemWindowsForms;
using SystemThreading;
namespace WindowsFormsApplication
{
public partial class Form : Form
{
private delegate void SetState(int x);//代理
public Form()
{
InitializeComponent();
ThreadCurrentThreadName = Main;//主线程命名
ConsoleWriteLine(ThreadCurrentThreadName);
}
private void TempFunction() //中转函数用来连续多次调用目标函数并模拟延时
{
for (int i = ; i < ;i++ )
{
ThreadFunction(i);
ThreadSleep();
}
}
private void ThreadFunction(int x) //实际控件操作函数
{
if (labelInvokeRequired) //用委托来操作
{
SetState ss = new SetState(ThreadFunction);
Invoke(ssnew object[]{x});
ConsoleWriteLine(ThreadCurrentThreadName);
}
else //普通方式操作
{
labelText = xToString();
labelUpdate();
ConsoleWriteLine(ThreadCurrentThreadName);
}
}
private void button_Click(object sender EventArgs e) //主线程的按钮操作用来显示区别所在
{
labelText = textBoxText;
}
private void button_Click(object sender EventArgs e) //按下按钮后开始多线程操作
{
Thread th = new Thread(new ThreadStart(TempFunction));
thIsBackground = true;
thName = kidfruit;
thStart();
}
private void backgroundWorker_DoWork(object sender DoWorkEventArgs e) //使用BackgroundWorker控件
{
ThreadSleep(); //模拟操作延时
}
private void backgroundWorker_RunWorkerCompleted(object sender RunWorkerCompletedEventArgs e) //BackgroundWorker耗时操作结束后
{
labelText = DateTimeNowToLongTimeString();
}
private void button_Click(object sender EventArgs e) //开始BackgroundWorker的耗时操作
{
backgroundWorkerRunWorkerAsync();
}
}
}