|
-
May 11th, 2009, 01:17 AM
#1
Control Refresh
Code:
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 ?
-
May 11th, 2009, 01:33 AM
#2
Re: Control Refresh
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.
-
May 11th, 2009, 02:04 AM
#3
Re: Control Refresh
You could call Application.DoEvents() in the loop to allow the app to process the current messages in the queue.
Code:
for(i=0;i<1000;i++)
{
progressBar1.Increment(1);
label2.Text = i.ToString()+ " record processed";
Application.DoEvents();
}
-
May 11th, 2009, 02:10 AM
#4
Re: Control Refresh
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.
Code:
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;
}
}
Last edited by BigEd781; May 11th, 2009 at 02:21 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|