问题描述
|
我是Web开发人员,并且正在尝试进入多线程编程。
在一种形式上,我试图使用异步委托在第二个线程中运行一种计算值的方法。
我还希望通知进度条以显示UI线程的实际进度。
delegate void ShowProgressDelegate(int total,int value);
delegate void ComputeDelegate(int value);
//Some method simulating sophisticated computing process
private void Compute(int value)
{
ShowProgress(value,0);
for (int i = 0; i <= value; i++)
{
ShowProgress(value,i);
}
}
//Method returning values into UI thread
private void ShowProgress(int total,int value)
{
if (!this.InvokeRequired)
{
ComputeButton.Text = value.ToString();
ProgressBar.Maximum = total;
ProgressBar.Value = value;
}
else
{
ShowProgressDelegate showDel = new ShowProgressDelegate(ShowProgress);
this.BeginInvoke(showDel,new object[] { total,value });
}
}
//firing all process
private void ComputeButton_Click(object sender,EventArgs e)
{
ComputeButton.Text = \"0\";
ComputeDelegate compDel = new ComputeDelegate(Compute);
compDel.BeginInvoke(100000,null,null);
}
当我运行此命令时,一切都在进行计算,没有任何问题,只是它仍在UI线程中运行(我想是这样,因为当我单击表单上的某些按钮时,它冻结了)。
为什么?我还使用相同的代码附加了可构建的示例项目(VS2010):http://osmera.com/windowsformsapplication1.zip
感谢您的帮助。
解决方法
在显示的代码中,除了更新进度条外,您什么都没有做-因此,有成千上万的UI消息需要封送,但在非UI线程中没有发生任何重大变化。
我怀疑,如果您开始在ѭ1中模拟真实的作品,您会发现它的行为更加合理。您需要确保不要像现在那样用进度更新来淹没UI线程。