在做GUI界面程序的时候,经常会遇到执行长时间方法的需求,当执行长时间方法的同时,再去点击界面,界面就会出现“卡死、假死”的现象,这是因为界面GUI线程被阻塞而导致暂时无响应。解决的方法有很多种,下面介绍C#组件BackgroundWorker的使用方法。

//异步执行,避免界面卡死, BackgroundWorker对象
private BackgroundWorker bw = new BackgroundWorker(); bw.WorkerReportsProgress = true;
//bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); //执行长时间方法
private void btnLongtime_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
} /// <summary>
/// BackgroundWorker执行的长时间方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
for(int i = ; i < ; i++)
{ } } /// <summary>
/// 事件执行完成的回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("执行完毕", "对话框"); }

参考

[1]:How to: Use a Background Worker

05-11 15:41