简体   繁体   中英

Any reason why Winforms Timer does not tick?

I have multiple timers running on my windows app. Each timer_tick runs a code. Right now I am working on two processes.

private async void tmrProcessDelay_Tick
private async void tmrAutopay_Tick

Just recently added the tmrAutopay as an added process so that instead of sequential process, I made them work at the same time. The problem I am having is that I am not able to restart the process of the Autopay.

Timers are declared at the top as an instance when form loads.

private System.Windows.Forms.Timer tmrProcessDelay = new System.Windows.Forms.Timer();
private System.Windows.Forms.Timer tmrAutopay = new System.Windows.Forms.Timer();

tmrAutopay.Interval = 2000;
tmrAutopay.Enabled = false;
tmrAutopay.Tick += new EventHandler(tmrAutopay_Tick);

private async void tmrAutopay_Tick(object sender, EventArgs e)
    {
        messagebox("tick"); // correcting this one
        txtNotes.AppendText("tick"); 
        tmrAutopay.Enabled = false;
        // do some code
        tmrAutopay.Enabled = true;
    }

EDIT: as per Michael Randall suggestion, I tried adding break point at the top. I got the issue. Just on the logic. I just thought that it doesn't start again because "tick" only appends once, so I assumed it only ran once. When I went adding the break point, it ticked again, but for some reason, it did not appendText , reason I did assume things. Going back to the problem, due to the existing logic, after

  1. called tick one - appendtext
  2. enabled = true - ticked but did not append
  3. due to logic, it did not go to enabled = true again

The timer tick only runs after I enabled it the first time, then when its ticks, I set it to false to do some code then start it again after finishing.

I have yet to try this system timer solution, and also saw some post that timers won't run on background process, since I can run it one time, it means it can.. But I just wanna ask before I change timers if there are any reasons why I am having this issue?

if you want to make like background process then you can do window service application and implement more than one timer in that code. I had good working experience with this type of application and I am confident that it will work without any issue with multiple timers. the only thing you need to be careful in code is that in case if some code takes longer than expected and more than timer interval then it will start another thread which could end up as deadlock for that timer or crash the application. Each timer works independently and creates a new thread each time when it ticks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM