方法一:async + await + Task
// 开始
private async void btnStart_Click(object sender, EventArgs e)
{
string message = await GetMessage();
MessageBox.Show(message);
}
// 一个耗时任务
private async Task<string> GetMessage()
{
return await Task<string>.Run(() =>
{
Thread.Sleep(10000);
return "Hello World";
});
}
方法二:使用BackgroundWorker组件
public Form1()
{
InitializeComponent();
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += DoWork;
this.backgroundWorker1.ProgressChanged += ProgressChanged;
this.backgroundWorker1.RunWorkerCompleted += RunWorkerCompleted;
}
// 开始
private void btnStart_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
return;
}
backgroundWorker1.RunWorkerAsync();
}
// DoWork
private void DoWork(object sender, DoWorkEventArgs e)
{
int max = pgbStatus.Maximum;
for (int i = 1; i <= max; i++)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(1000);
}
}
// ProgressChanged
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbStatus.Value = e.ProgressPercentage;
}
// RunWorkerCompleted
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("完成");
}
方法三:Task + 委托(回调函数)
// 开始
private void btnStart_Click(object sender, EventArgs e)
{
Task task = Task.Run(() =>
{
int max = progressBar1.Maximum;
for (int i = 1; i <= max; i++)
{
UpdateValue(i);
Thread.Sleep(1000);
}
});
}
// 处理线程
private void UpdateValue(int num)
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new Action<int>(UpdateValue), new object[] { num });
}
else
{
progressBar1.Value = num;
}
}
版权归原作者 glad_666 所有, 如有侵权,请联系我们删除。