Click to See Complete Forum and Search --> : Control Refresh
Saeed
May 11th, 2009, 01:17 AM
for(i=0;i<1000;i++)
{
progressBar1.Increment(1);
label2.Text = i.ToString()+ " record processed";
}
Why is it that some controls (i.e, :label2.text or textboxes ) do not get updated in the loop apart from the progressBar ?
BigEd781
May 11th, 2009, 01:33 AM
because of the way that Windows works. There is what's called a message pump which is like a queue. When you are in a loop like that, the message pump does not process, so even though you do actually change the properties of the label, no Paint messages are processed, so the window does not refresh. You know when you see that little hourglass cursor when a program is 'hanging"? You see that because the program is unresponsive for more than 5 seconds, i.e., it is not processing window messages. I suggest you read a bit about the Windows API.
cilu
May 11th, 2009, 02:04 AM
You could call Application.DoEvents() in the loop to allow the app to process the current messages in the queue.
for(i=0;i<1000;i++)
{
progressBar1.Increment(1);
label2.Text = i.ToString()+ " record processed";
Application.DoEvents();
}
BigEd781
May 11th, 2009, 02:10 AM
You could, but that can lead to problems with re-entrancy and there are few situations using .NET where DoEvents is a necessary approach. You can do your processing in a BackgroundWorker and notify the UI in its DoWork event.
public partial class Form1 : Form
{
public Form1( )
{
InitializeComponent( );
}
private void button1_Click( object sender, EventArgs e )
{
BackgroundWorker worker = new BackgroundWorker( );
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync( );
}
void worker_DoWork( object sender, DoWorkEventArgs e )
{
for ( int i = 0 ; i < 1000000000 ; ++i )
{
this.Invoke( new FooDelegate( Foo ), new object[ ] { i.ToString( ) } );
}
}
private delegate void FooDelegate( string text );
private void Foo( string text )
{
label1.Text = text;
}
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.