在子執行緒執行長時間工作(如下載),需安全更新 UI 進度條。
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
new Thread(new ThreadStart(StartDownload)).Start();
}
public void StartDownload()
{
Downloader downloader = new Downloader();
downloader.onDownLoadProgress += downloader_onDownLoadProgress;
downloader.Start();
}
void downloader_onDownLoadProgress(long total, long current)
{
if (this.InvokeRequired)
{
this.Invoke(new Downloader.dDownloadProgress(downloader_onDownLoadProgress), total, current);
}
else
{
this.progressBar1.Maximum = (int)total;
this.progressBar1.Value = (int)current;
}
}
}
public class Downloader
{
public delegate void dDownloadProgress(long total, long current);
public event dDownloadProgress onDownLoadProgress;
public void Start()
{
for (int i = 0; i < 100; i++)
{
if (onDownLoadProgress != null)
onDownLoadProgress(100, i);
Thread.Sleep(100);
}
}
}
}
關鍵點:使用 InvokeRequired 判斷是否需跨執行緒呼叫,透過 Invoke 將更新委派回 UI 執行緒。