The timer used in the task does not tick.

Asked 2 years ago, Updated 2 years ago, 43 views

I created the following program in .Net FrameWork 4.5.
When running on Task, timer does not reach timer_Tick and
If you just call it, it will go to timer_Tick.
Why does the difference between the two occur?
Thank you for your cooperation.

classa
{
     Timer timer = new Timer();
     publica()
     {
          timer.Tick+=timer_Tick;
     }
     public void start()
     {
          timer.Interval = 1000;
          timer.Start();
     }
     void timer_Tick (object sender, EventArgse)
     {
        return;
     }
}

class main
{
     public main()
     {
        a A = new a();
        Task.Run(()=>{A.Start();});// Do not tick.
        A. Start(); // Tick.
     }
}

c#

2022-09-29 22:38

2 Answers

Self-resolved, but explain why.

  • System.Windows.Forms.Timer starts running on the UI thread and is called on the UI thread.If the thread you ran does not appear in the UI thread, it will not work because there is no way to call it.
  • System.Timers.Timer is invoked from the thread pool.Run from any thread.

So when it comes to the code in the questionnaire, it doesn't make much sense to run from Task.Run() and you can run it from the main thread.


2022-09-29 22:38

System.Windows.Forms.Timer.
By using System.Timers.Timer, I understand that even if I use it as a Task, it also ticks (Elapsed).


2022-09-29 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.