I have a simple form that is supposed to start a timer, perform a time-consuming operation, and update a progress bar at a certain interval while that operation is working. Right now, the time-consuming operation is bound to a SearchButton. However, nothing happens with the progress bar, even though the time-consuming operation (in this case a download) does take several seconds:
public partial class Form1 : Form
{
System.Windows.Forms.Timer searchProgressTimer;
public Form1()
{
InitializeComponent();
this.searchProgressTimer = new System.Windows.Forms.Timer();
}
private void InitializeTimer()
{
this.searchProgressTimer.Interval = 250;
this.searchProgressTimer.Tick += new EventHandler(searchProgressTimer_Tick);
}
void searchProgressTimer_Tick(object sender, EventArgs e)
{
searchProgressBar.Increment(1);
if (searchProgressBar.Value == searchProgressBar.Maximum)
this.searchProgressTimer.Stop();
}
private void SearchDatabase_Click(object sender, EventArgs e)
{
this.searchProgressTimer.Start();
// Time-consuming operation
String filename = @"http://www.bankofengland.co.uk/publications/Documents/quarterlybulletin/qb0704.pdf";
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(filename), @"file.pdf");
int test;
for (int i = 0; i < 100000; i++)
for (int j = 0; j < 100000; j++)
test = i + j;
this.searchProgressTimer.Stop();
}
}
(The functions are named a tad strangely because the actual time-consuming operation is a database search, but that code, although working correctly, is extremely long and involved).
Debugging this code just shows me that the SearchButton_Click event handler fires correctly, but the code never jumps to the searchProgressTimer_Tick event handler. Any ideas?
So 1) I don’t see a call to InitializerTimer() anywhere.
and 2) System.Windows.Forms.Timer raises its tick event on the UI thread.. the very same thread you are doing your time consuming op on. You will need to yield control to the message pump once in a while in order for the even to be processed.