1

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

感谢帮助新手。

4

1 回答 1

4

在您显示的代码中,除了更新进度条之外,您什么也没做 - 因此有数千条 UI 消息要编组,但在非 UI 线程中没有发生任何重大事件。

如果您开始在 中模拟实际工作Compute,我怀疑您会发现它的行为更加合理。您需要确保不会像现在这样使用进度更新淹没 UI 线程。

于 2011-05-24T12:48:55.207 回答