Selman22的解決方案是好的,另一種方式來使用建議Thread.Sleep();
,不會凍結您的GUI是使用一個後臺工作及其進展情況改變的事件。 你可以做一些循環迭代100次,每次迭代你做一個小的Thread.Sleep();
,每次迭代後你發送一個改變的進度並更新你的進度條。
後臺工作應該是這樣的:
private void BackgroundWorkerStartEvent(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void BackgroundWorkerCancelBeforeWorkIsDoneEvent(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation)
{
backgroundWorker1.CancelAsync();
}
}
private void DoWorkEvent(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
const int loopnumber = 100;
for (int i = 1; i <= loopnumber; i++)
{
if (worker != null && worker.CancellationPending)
{
e.Cancel = true;
break;
}
System.Threading.Thread.Sleep(100);
if (worker != null) worker.ReportProgress(i * 100/loopnumber);
}
}
private void ProgressChangedEvent(object sender, ProgressChangedEventArgs e)
{
//...update your progress bar or something.
}
private void RunWorkerCompletedEvent(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
//...Do what you do if the backgroundworker go cancelled...
}
else if (e.Error != null)
{
//...Error displaying...
}
else
{
//...Do what you do if it worked fine...
}
}
正在尋找這個人,但不記得如何做到這一點。好的解決方案 – DatRid 2014-09-22 10:30:21
夥計,這工作正常! TNX – 2014-09-22 10:52:37