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.
}
}
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.
System.Windows.Forms.Timer.
By using System.Timers.Timer, I understand that even if I use it as a Task, it also ticks (Elapsed).
© 2024 OneMinuteCode. All rights reserved.