Is it possible to synchronize the timer of C#?

Asked 2 years ago, Updated 2 years ago, 35 views

private void Form1_Load (object sender, EventArgse)
    {

        AutoResetEvent autoEvent=new AutoResetEvent(false);
        StatusChecker statusChecker = new StatusChecker();

        // Create the delete that invokes methods for the timer.
        TimerCallback timerDelegate=
            new TimerCallback(statusChecker.CheckStatus);

        // Timer start
        Console.WriteLine("Start the {0} timer.\n",
            DateTime.Now.ToString("h:mm:ss.fff"));

        System.Threading.Timer stateTimer=
                // Last two values → time to initial run, run interval in milliseconds
                new System.Threading.Timer(timerDelegate, autoEvent, 0,10000);

        // Timer wait time is unlimited if -1 (written in milliseconds if you want to be finite)
        autoEvent.WaitOne(-1, false);
        // Open Timer
        stateTimer.Dispose();

    }

    class StatusChecker
    {
        public StatusChecker()
        {
        }

        // This method is called by the timer delete.
        public void CheckStatus (Object stateInfo)
        {
            AutoResetEvent= (AutoResetEvent) stateInfo;

            // Write here what you want to do in a certain amount of time
            MessageBox.Show("Test";

        }
    }

For example, if you don't erase the "test" message,
After a certain period of time, I would like to skip displaying "test" again in the timer.
Is there no other way but to use the flag?

visual studio express 2015 windows 10 (64bit)

c#

2022-09-30 14:59

1 Answers

StatusChecker You can manipulate stateTimer as well as autoEvent by letting the instance have the information it needs.

class StatusChecker{
    public AutoResetEvent AutoEvent {get;}
    public System.Threading.Timer StateTimer {get;}
    public StatusChecker (AutoResetEvent autoEvent, System.Threading.Timer stateTimer) {
        AutoEvent = autoEvent;
        StateTimer = stateTimer;
    }

There are three types of timers in the .NET Framework:

  • System.Threading.Timer:low-level timer
  • System.Timers.Timer—Low-level timers wrapped for ease of handling
  • System.Windows.Forms.Timer: GUI-only timer, independent of the previous two

As you can see from the description, System.Threading.Timer should not be used very often.At a minimum, System.Timers.Timer makes it easier to stop and resume.However, you should use System.Windows.Forms.Timer for GUI processing.In that case, if you wait for the AutoResetEvent, the GUI will lock up.
I think we need to review the design.


2022-09-30 14:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.