Reputation: 486
I want to automatically refresh my result in label in Windows Form. This code works, but text in label isn't changed. In my opinion program have to stop their operation to refresh label. I also tried http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx and http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(EHInvalidOperation.WinForms.IllegalCrossThreadCall);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true, but it doesn't work neither. It says that thread is different and they can not do it. Also MSNDa code doesn't work for me :(.
private void button1_Click(object sender, EventArgs e)
{
while (true)
{
CaluclateTime();
Thread.Sleep(1000);
}
}
private void CaluclateTime()
{
DateTime zeroDateTime = new DateTime(2014, 9, 16, 15, 00, 0);
//zeroDateTime is a future :).
DateTime now = DateTime.Now;
TimeSpan duration = zeroDateTime - now;
label1.Text = String.Format("Time zero is in: {0}", duration.ToString());
}
Upvotes: 0
Views: 1208
Reputation: 7934
You should rather do the processing in a background thread but if you insist on doing it in a single thread, you should read this answer : Force GUI update from UI Thread
Edit (for relevance): Calling Application.DoEvents()
causes the Windows Forms UI to process any outstanding UI events, including Windows Control updates such as label text updates. Call this method immediately after updating the label Text property.
Edit (for overall improvement): Having long running processes running in a background thread allows you the flexibility of having the user perform other actions (if you desire) while the long running operation is being performed. It builds a better user experience for users as the UI is responsive at all times which is desirable to the user.
Background thread technologies in C# include:
Upvotes: 2
Reputation: 101701
You can take advantage of async / await
feature:
private async void button1_Click(object sender, EventArgs e)
{
while (true)
{
CaluclateTime();
await Task.Delay(1000);
}
}
And change your CalculateTime
method like this:
if (this.InvokeRequired)
this.Invoke(() => label1.Text = String.Format("Time zero is in: {0}", duration.ToString()));
else
label1.Text = String.Format("Time zero is in: {0}", duration.ToString());
Also don't forget to stop your loop.
Upvotes: 1