前些日子,看了网上几个例子,总结一下:
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;
//using System.Windows.Forms.Application;
namespace UIWorkTask
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread uiThread=null;//UI线程
Thread wkThread = null;//工作线程
private void Form1_Load(object sender, EventArgs e)
public void UpdateProgressThread() {//UI线程的具体操作,此处给一个进度条
int i;
for (i = 0; i < 100; i++) {
Thread.Sleep(100);
this.Invoke(new Action<int>(this.UpdateProgress), i);//UI设置是不能直接在线程中进行的,必须使用代理
}
public void UpdateProgress(int i) {//更新UI设置的具体实现
this.progressBar1.Value = i;
public void work() {//工作线程
Thread.Sleep(2000);
uiThread.Suspend();
uiThread.Resume();
MessageBox.Show("work thread is working ...");
private void button1_Click(object sender, EventArgs e)//添加一个按钮,点击按钮开始两个线程工作
uiThread = new Thread(new ThreadStart(UpdateProgressThread));
uiThread.Start();
wkThread = new Thread(new ThreadStart(work));
wkThread.Start();
}
}
运行即可.
这个程序不具有实际应用,因为程序的UI更新往往和工作进展相关联,即UI线程和work线程需要互相通知对方,即两个线程之间有信息传递.