1
我是Web开发人员,我正在尝试进入多线程编程。 在一个窗体上,我试图运行一个使用异步委托在第二个线程中计算值的方法。 我也想要一个进度条显示UI线程的实际进度已被通知。C#Winforms:BeginInvoke仍然在同一个线程上运行?
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
感谢您帮助neewbie。
...比如'Thread.Sleep(700)' – SLaks 2011-05-24 12:57:01