在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线程执行,从而避免抛出异常。