前些日子,看了網上幾個例子,總結一下:
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線程需要互相通知對方,即兩個線程之間有資訊傳遞.