0

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());
    }
Jaryn
  • 446
  • 4
  • 16
  • If you use a `System.Timers.Timer` timer, make sure you set the `SynchronizingObject` property. See [this answer](http://stackoverflow.com/a/24086028) for an example. Without it, it will throw CrossThreadExceptions. – JW Lim Jul 09 '14 at 14:22

2 Answers2

2

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:

Community
  • 1
  • 1
toadflakz
  • 7,764
  • 1
  • 27
  • 40
  • Could you add the relevant parts from that link into your answer? Link-only answers are frowned upon here, as they tend to become useless if the linked page is changed or removed. – JW Lim Jul 09 '14 at 14:44
  • Great! Your answer could be further improved on if you could add an example on how to use that method, and also provide some elaboration on why you suggest to do the processing in a background thread (just saying something is bad without explaining why isn't very helpful!). – JW Lim Jul 09 '14 at 14:51
1

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.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184