c# - how to timer inside loop? -


i want send alert today @ different time interval. wrote code follows, never calls method sendalert(). go wrong?

//aletfortoday gives me @ time need send alert. (int = 0; < alertfortoday.count();i++) {     timespan day = new timespan(24, 00, 00);    // 24 hours in day.     timespan = timespan.parse(datetime.now.touniversaltime().tostring("hh:mm"));       timespan activationtime = timespan.parse(alertfortoday.dt.tostring("hh:mm"));   // 11:45 pm                   timespan timeleftuntilfirstrun = ((day - now) + activationtime);     if (timeleftuntilfirstrun.totalhours > 24)     timeleftuntilfirstrun -= new timespan(24, 0, 0);     system.timers.timer timers = new system.timers.timer();     timers.interval = timeleftuntilfirstrun.totalmilliseconds;     timers.autoreset = false;     timers.elapsed += new system.timers.elapsedeventhandler((sender, e) =>     {                                 sendalert(alertfortoday[i]);     });     timers.start(); } 

you're closing on loop variable i. closures close on variables, not values, timer's event using value of i when fires, not when added handler. @ point in time value of i after end of collection, event ever throwing index out of range exception.

create copy of i inside body of for loop , close on copy.

that, or use foreach loop iterate alertfortoday rather for loop, because loop variable of foreach re-created on each iteration, rather re-using same variable for loop.


Comments

Popular posts from this blog

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

linux - disk space limitation when creating war file -

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