Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7784727
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T20:08:28+00:00 2026-06-01T20:08:28+00:00

Playing round with Timers. Context: a winforms with two labels. I would like to

  • 0

Playing round with Timers.
Context: a winforms with two labels.

I would like to see how System.Timers.Timer works so I’ve not used the Forms timer.
I understand that the form and myTimer will now be running in different threads.
Is there an easy way to represent the elapsed time on lblValue in the following form?

I’ve looked here on MSDN but is there an easier way !

Here’s the winforms code:

using System.Timers;

namespace Ariport_Parking
{
  public partial class AirportParking : Form
  {
    //instance variables of the form
    System.Timers.Timer myTimer;
    int ElapsedCounter = 0;

    int MaxTime = 5000;
    int elapsedTime = 0;
    static int tickLength = 100;

    public AirportParking()
    {
        InitializeComponent();
        keepingTime();
        lblValue.Text = "hello";
    }

    //method for keeping time
    public void keepingTime() {

        myTimer = new System.Timers.Timer(tickLength); 
        myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);

        myTimer.AutoReset = true;
        myTimer.Enabled = true;

        myTimer.Start();
    }


    void myTimer_Elapsed(Object myObject,EventArgs myEventArgs){

        myTimer.Stop();
        ElapsedCounter += 1;
        elapsedTime += tickLength; 

        if (elapsedTime < MaxTime)
        {
            this.lblElapsedTime.Text = elapsedTime.ToString();

            if (ElapsedCounter % 2 == 0)
                this.lblValue.Text = "hello world";
            else
                this.lblValue.Text = "hello";

            myTimer.Start(); 

        }
        else
        { myTimer.Start(); }

    }
  }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T20:08:29+00:00Added an answer on June 1, 2026 at 8:08 pm

    I guess your code is just a test so I won’t discuss about what you do with your timer. The problem here is how to do something with an user interface control inside your timer callback.

    Most of Control‘s methods and properties can be accessed only from the UI thread (in reality they can be accessed only from the thread where you created them but this is another story). This is because each thread has to have its own message loop (GetMessage() filters out messages by thread) then to do something with a Control you have to dispatch a message from your thread to the main thread. In .NET it is easy because every Control inherits a couple of methods for this purpose: Invoke/BeginInvoke/EndInvoke. To know if executing thread must call those methods you have the property InvokeRequired. Just change your code with this to make it works:

    if (elapsedTime < MaxTime)
    {
        this.BeginInvoke(new MethodInvoker(delegate 
        {
            this.lblElapsedTime.Text = elapsedTime.ToString();
    
            if (ElapsedCounter % 2 == 0)
                this.lblValue.Text = "hello world";
            else
                this.lblValue.Text = "hello";
        }));
    }
    

    Please check MSDN for the list of methods you can call from any thread, just as reference you can always call Invalidate, BeginInvoke, EndInvoke, Invoke methods and to read InvokeRequired property. In general this is a common usage pattern (assuming this is an object derived from Control):

    void DoStuff() {
        // Has been called from a "wrong" thread?
        if (InvokeRequired) {
            // Dispatch to correct thread, use BeginInvoke if you don't need
            // caller thread until operation completes
            Invoke(new MethodInvoker(DoStuff));
        } else {
            // Do things
        }
    }
    

    Note that current thread will block until UI thread completed method execution. This may be an issue if thread’s timing is important (do not forget that UI thread may be busy or hung for a little). If you don’t need method’s return value you may simply replace Invoke with BeginInvoke, for WinForms you don’t even need subsequent call to EndInvoke:

    void DoStuff() {
        if (InvokeRequired) {
            BeginInvoke(new MethodInvoker(DoStuff));
        } else {
            // Do things
        }
    }
    

    If you need return value then you have to deal with usual IAsyncResult interface.

    How it works?

    A GUI Windows application is based on the window procedure with its message loops. If you write an application in plain C you have something like this:

    MSG message;
    while (GetMessage(&message, NULL, 0, 0))
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }
    

    With these few lines of code your application wait for a message and then delivers the message to the window procedure. The window procedure is a big switch/case statement where you check the messages (WM_) you know and you process them somehow (you paint the window for WM_PAINT, you quit your application for WM_QUIT and so on).

    Now imagine you have a working thread, how can you call your main thread? Simplest way is using this underlying structure to do the trick. I oversimplify the task but these are the steps:

    • Create a (thread-safe) queue of functions to invoke (some examples here on SO).
    • Post a custom message to the window procedure. If you make this queue a priority queue then you can even decide priority for these calls (for example a progress notification from a working thread may have a lower priority than an alarm notification).
    • In the window procedure (inside your switch/case statement) you understand that message then you can peek the function to call from the queue and to invoke it.

    Both WPF and WinForms use this method to deliver (dispatch) a message from a thread to the UI thread. Take a look to this article on MSDN for more details about multiple threads and user interface, WinForms hides a lot of these details and you do not have to take care of them but you may take a look to understand how it works under the hood.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I started playing around with OpenGL and GLUT. I would like to draw some
Here's a quick and dirty round corners technique I've been playing around with. <!--
I have been playing round with the Async CTP this morning and have a
I have three images that I would like to join in a widget I'm
I am playing around with PRNGs (like Mersenne Twister and rand() function of stdlib)
I was playing around with function expressions and trying to get my head round
I am playing with Parallax scrolling like on that nike site . So I
Playing around with Python - tkInter - Entry widget - when I use validatecommand
Playing with the new(ish) url rewriting functionality for web forms, but I'm running into
Playing with jquery for the first time, and I'm trying to get a simple

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.