c# - Execute method every specific time(ms) -


i want execute method takes inputs every specific time (such 25 ms) under following conditions:

  1. run method every 25 ms.
  2. if method delay greater 25 ms, stop execution , start beginning new inputs.

hint: used following code doesn't stopped execution if method delay > 25 ms

private timer timer1;  public void inittimer() {    timer1 = new timer();    timer1.tick += new eventhandler(timer1_tick);    timer1.interval = 1000/40;     timer1.start(); }  private void timer1_tick(object sender, eventargs e) {    mymethod() }     

thanks

i didn't chance run , check 100% accurate, should give idea how use task solve problem:

public class {     public task _mymethodtask;     public cancellationtokensource _canceltoken;     public timer _mytimer;     public random _rnd;      public void start()     {         _rnd = new random((int)datetime.now.ticks);         _mytimer = new timer(timerelapsedhandler);         _mytimer.change(25, 25);     }      public void timerelapsedhandler(object state)     {         if (!_mymethodtask.iscompleted)         {                             //the current task taking long             _canceltoken.cancel();         }          _canceltoken = new cancellationtokensource(timespan.frommilliseconds(25));         _mymethodtask = new task(() => mymethod(), _canceltoken.token);     }      public void mymethod()     {         stopwatch sw = new stopwatch();         sw.start();         int delaytimems = _rnd.next(5, 50);          while (sw.elapsedmilliseconds < delaytimems)         {             try             {                 _canceltoken.token.throwifcancellationrequested();                 thread.sleep(1);             }             catch (taskcanceledexception)             {                 return;             }          }     } } 

what happening uses timer (in case system.threading.timer) runs every 25 milliseconds. starts new task cancellation time of 25 milliseconds. task mymethod(), , simulate long running process delays random time. can add console.writeline or debug.writeline calls see working.

the important thing note have call _canceltoken.token.throwifcancellationrequested(); periodically, not once. method throws exception if cancellation requested , can clean before exiting if need be. if don't call it, task not cancel.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -