开发者

C# Winforms: BeginInvoke still running on same thread?

I'm web developer and I'm trying to step into multithreading programming. On one form I'm trying to run a method computing values in a second thread using asynchronous delegates. I also want a progress bar showing actual progress in UI thread been notified.

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(开发者_如何学Pythonint 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);
}

When I run this, everything is computing without any problem except it is still running in UI thread (I suppose so, because it freezes when I click some button on the form).

Why? I also attach buildable sample project (VS2010) with same code: http://osmera.com/windowsformsapplication1.zip

Thanks for helping neewbie.


In the code you've shown, you're doing nothing other than updating the progress bar - so there are thousands of UI messages to marshal, but nothing significant happening in the non-UI thread.

If you start simulating real work in Compute, you'll see it behave more reasonably, I suspect. You need to make sure you don't swamp the UI thread with progress updates like you are doing now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜