我有以下代码以异步方式更新进度条,我注意到了 它通过调用MessageBox来实现异步行为。在这种情况下,它完美地运行 但是当我给出1s(1000)的睡眠时,MessageBox不会弹出,并且完整的进度条会立即填充。 请告诉我为什么会这样。
private void button1_Click(object sender, EventArgs e)
{
Update_Async async = new Update_Async(Update_Async_method);
progressBar1.BeginInvoke(async,10);
MessageBox.Show("Updation In Progress");
}
public void Update_Async_method(int a)
{
this.progressBar1.Maximum = a;
for (int i = 1; i <= a; i++)
{
progressBar1.Value = a;
Thread.Sleep(10);
//Thread.Sleep(1000);
}
}
答案 0 :(得分:0)
如果您希望委托异步运行,请尝试使用Update_Async.BeginInvoke(async, 10)
,但是您必须将更新的线程检查交叉到进度条。
回应你的评论,与你已经做的非常相似,
void UpdatingFunction(int value)
{
if (this.progressBar.InvokeRequired)
{
this.progressBar.BeginInvoke(UpdatingFunction, value);
return;
}
// Invoke not required, work on progressbar.
}
这也解释了控件的Invoke
方法的用途。
答案 1 :(得分:0)
Delegate.BeginInvoke
将在一个线程中运行一次方法,然后将其处理掉。如果你想在一个线程中反复做一些工作并返回中间结果,那么这是一个糟糕的选择。如果这是你想要的,你应该使用BackgroundWorker
。高度缩写的片段:
BackgroundWorker bw;
YourFormConstructor()
{
...
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += BackgroundCalculations;
bw.ProgressChanged += ShowBackgroundProgress;
}
private void button1_Click(object sender, EventArgs e)
{
bw.RunWorkerAsync(10);
}
void ShowBackgroundProgress(object sender, ProgressChangedEventArgs e)
{
this.progressBar.Value = e.ProgressPercentage;
}
static void BackgroundCalculations(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
int max = (int)e.Argument;
for (int i = 0; i < max; i++)
{
bw.ReportProgress(i * 100 / max);
Thread.Sleep(10);
}
bw.ReportProgress(100);
}
}