我是网络开发人员,我正在尝试进入多线程编程。在一种形式上,我尝试使用异步委托在第二个线程中运行计算值的方法。我还希望通知显示 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
感谢帮助新手。