views:

516

answers:

1

I have a simple program which loops through a resultset when a button is pressed and performs actions against this resultset (stored in a DataTable). During the loop I update the text of a RichTextBox, 2 labels, and a ToolStripStatusLabel. These are not refreshing during the loop so after each item is processed in the loop I do a this.Refresh(). This works unless I click on anything in the program, at which time it says it's not responding, and nothing is refreshed in the form until the foreach loop completes.

private void myBtn_Click(object sender, EventArgs e)
{
    // Query database and store results in DataTable dt.

    foreach (DataRow dr in dt.Rows)
    {
       // Process row data.
       // Update RichTextBox, labels, and ToolStripStatusLabel.
       this.Refresh();
    }
}

Is something wrong here? Is there a better way to do this? This is a Windows Forms application using C#.

+5  A: 

It says "not responding" because you're tying up the GUI thread. If you have a lengthy operating to perform, consider using a background thread instead.

Check out BackgroundWorker to get started.

And here's a threading tutorial, just in case.

Jon B
If I move this logic to a background thread wouldnt it lock up on that thread as well? Or maybe call the this.Refresh in the main thread from the background thread?
Chris Klepeis
Your background thread would be busy, but it wouldn't affect the GUI (you program would remain resonsive). You'll need to use Invoke (or BeginInvoke) to make changes to your GUI from the background thread, too.
Jon B
Got it working by processing this logic in a background worker and updating the ui with delegates / invoke. Thanks
Chris Klepeis