java不支持多线程 C#多线程操作控件的两种安全方式
C#多线程操作控件的两种安全方式
实现的功能是
按button 之后 label 会每 毫秒显示一次数字 数字从 到 (委托方式实现)
按button 之后 模拟耗时操作 秒后label 显示为当前时间 (BackgroundWorker方式实现)
在 执行的时候 按button 可以将label 的内容改为textbox 的内容 (此处为主线程控制 用于显示多线程未死锁主线程)
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 WindowsFormsApplication

{
public partial class Form : Form
{
private delegate void SetState(int x);//代理
public Form ()
{
InitializeComponent();
Thread CurrentThread Name = Main ;//主线程命名
Console WriteLine(Thread CurrentThread Name);
}
private void TempFunction() //中转函数 用来连续多次调用目标函数并模拟延时
{
for (int i = ; i < ;i++ )
{
ThreadFunction(i);
Thread Sleep( );
}
}
private void ThreadFunction(int x) //实际控件操作函数
{
if (label InvokeRequired) //用委托来操作
{
SetState ss = new SetState(ThreadFunction);
Invoke(ss new object[]{x});
Console WriteLine(Thread CurrentThread Name);
}
else //普通方式操作
{
label Text = x ToString();
label Update();
Console WriteLine(Thread CurrentThread Name);
}
}
private void button _Click(object sender EventArgs e) //主线程的按钮操作 用来显示区别所在
{
label Text = textBox Text;
}
private void button _Click(object sender EventArgs e) //按下按钮后开始多线程操作
{
Thread th = new Thread(new ThreadStart(TempFunction));
th IsBackground = true;
th Name = kidfruit ;
th Start();
}
private void backgroundWorker _DoWork(object sender DoWorkEventArgs e) //使用BackgroundWorker控件
{
Thread Sleep( ); //模拟操作延时
}
private void backgroundWorker _RunWorkerCompleted(object sender RunWorkerCompletedEventArgs e) //BackgroundWorker耗时操作结束后
{
label Text = DateTime Now ToLongTimeString();
}
private void button _Click(object sender EventArgs e) //开始BackgroundWorker的耗时操作
{
backgroundWorker RunWorkerAsync();
}
}
lishixinzhi/Article/program/net/201311/13500