In VS 2010 I’m trying to read a text file on button click and set that value as the status button value. The text file will always contain a single line with a number between 0 and 100. I’m trying to do this in C++/CLI because I’m familiar with C++ but this seems like a whole different lang! This is what I have but it causes the GUI to crash. I know it’s the loops fault but I don’t know why, what’s the best (noob) way to approach this?
while (result<100)
{
StreamReader ^read=gcnew StreamReader("Status.txt");
String ^x=read->ReadLine();
read->Close();
Int32::TryParse(x, result);
progressBar1->Value= result;
}
You haven’t said whether you’re using WPF or WinForms for your GUI, but this answer applies equally to either.
If your while loop in in a button handler, that code is running on the UI thread. The UI thread is also responsible for redrawing the GUI. Since your button method isn’t returning, it’s never getting to the ‘repaint’ code, and the UI just stops.
You didn’t mention what is writing those integers 0 to 100 to a file. If it’s another thread in the same application, there are MUCH better ways of communicating the progress between threads.
I recommend that you replace that while loop with a
Timerobject of some sort. (There are appropriate classes, depending on whether you’re using WPF or WinForms.) Set the interval to something like 500 milliseconds, start the timer when your background task begins, and stop the timer when it ends. In the timer method, don’t have a while loop, just do it once.