2011-05-24 47 views
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。

回答

4

在你显示的代码中,除了更新进度条之外,你没有做任何事情 - 所以有数以千计的UI消息要封送,但在非UI线程中没有任何重大事件发生。

如果你开始模拟realCompute工作,你会发现它的行为更合理,我怀疑。您需要确保您不会像现在这样使用进度更新来吞噬UI线程。

+0

...比如'Thread.Sleep(700)' – SLaks 2011-05-24 12:57:01

相关问题