在C# WinForms中,可以使用多線程來執行耗時操作,從而避免UI線程被阻塞,導致應用程序無響應
System.Threading.Thread
類創建線程:using System;
using System.Threading;
using System.Windows.Forms;
namespace MultiThreadingExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(DoWork));
thread.Start();
}
private void DoWork()
{
// 在這里執行耗時操作
// ...
// 如果需要更新UI,請使用Invoke方法
Invoke((MethodInvoker)delegate
{
label1.Text = "操作完成";
});
}
}
}
Task
類(推薦):using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MultiThreadingExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void btnStart_Click(object sender, EventArgs e)
{
await Task.Run(() => DoWork());
}
private void DoWork()
{
// 在這里執行耗時操作
// ...
// 如果需要更新UI,請使用Invoke方法
Invoke((MethodInvoker)delegate
{
label1.Text = "操作完成";
});
}
}
}
BackgroundWorker
組件:using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace MultiThreadingExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
}
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// 在這里執行耗時操作
// ...
}
private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
label1.Text = "操作完成";
}
}
}
注意:在多線程環境下更新UI時,務必使用Invoke
或BeginInvoke
方法。這些方法將操作委托給UI線程執行,從而避免拋出異常。