views:

113

answers:

2

Hi,

I went through several examples posted online but I cant answer my question.

I have my 'p' variable that is being increased by 1 in the for loop. I want the UI to display the progress of calculation (to show how 'p' is increasing from 0 to 1000000). I do the calculation on the separate thread and the I call dispatcher to update the ResultBox in UI. Example:

 int p=0;

 ...

 private void GO(object sender, System.Windows.RoutedEventArgs e)
 {
        new Thread(delegate()
        {
            DoWork();
        }).Start();

}

    void DoWork()
    {
        for (int i = 0; i < 1000; i++)
        {
            for (int j = 0; j < 10000; j++)
            {
                p++;
                this.Dispatcher.BeginInvoke(delegate { ResultBox.Text = p.ToString(); });
            }
        }

    }

For some reason this doesn't work. However when I put Thread.Sleep(1) just before this.Dispatcher... it works as intended. Does it mean that the UI update (Dispatcher) is called too frequently therefore it freezes? Is there any other way to do it?

Thank you

A: 

Yes only doing p++ in your loop will not take much of time and inside silverlight, Dispatcher is nothing but a simple queue with delegates, and before silverlight can even update and process its UI, you are pumping too many values on the queue. Imagin what will happen if you keep on adding queue way to faster then the queue is dequeued, then eventually it will hit max limit as well. And eventually it will just stop. If your p++ is replaced with more time consuming task, then you may get good result.

You must know that our eye usually can see only updates of 30 fps, more then 30 updates per second will not be of any use at all, I will suggest your view update should be reduced to max 10 updates per second for best performance.

And for showing progress, I think 1 update per second is also enough. First always display updates very slowly, like

void DoWork() 
{ 
    for (int i = 0; i < 1000; i++) 
    { 
        for (int j = 0; j < 10000; j++) 
        { 
            p++; 
            if((p % 1000)==0){
                 this.Dispatcher.BeginInvoke(delegate 
                      { ResultBox.Text = p.ToString(); });
            } 
        } 
    } 

} 

Now you can increaes/decrease 1000 to some suitable multipler of 10 to adjust your visual update.

Akash Kava
A: 

Why not bind a property to your TextBox and the update the property value instead of poking at the textbox directly?

Scrappydog