Reputation: 625
I have read many answers on this question, and yet I still cannot get this to work. I have a simple C# WinForms app with a timer control. When the timer fires, I have some code do some processing. I want to update a textbox with status during this processing. But the textbox never gets updated until the eventhandler finishes. Please tell me how I can get the textbox to update during the processing.
Here is my code:
My Form:
public Form1()
{
InitializeComponent();
timer1.Interval = 60000;
timer1.Tick += new EventHandler(CheckStatus);
timer1.Start();
}
private void CheckStatus(object Sender, EventArgs e)
{
// Set the caption to the current time.
textBox1.AppendText(DateTime.Now.ToString() + Environment.NewLine);
ProcessStatus();
}
private void ProcessStatus()
{
textBox1.AppendText("Now updated" + Environment.NewLine);
}
If I step through my code, the textbox is not updated until I step out of CheckStatus. (I'm using Visual Studio 2017)
I have tried several things like what is found here: StackOverflow
Upvotes: 0
Views: 682
Reputation: 4395
When the timer ticks it's firing on the GUI thread. While the GUI thread is busy processing (I assume whatever you're doing takes a long time) all other GUI updates will pause.
You can run textBox.Update()
to force the update at that point, but that's not considered a best practice.
Instead, you should run your process on a background thread. One option is BackgroundWorker
and use the ProgressChanged
event to show your updates in your GUI.
Upvotes: 1