c# - How to preserve System.Threading.Timer when function is call again -
i doing simple system.threading.timer testing because want use in window services . problem facing when call again function timer , existing running time gone , how preserve ?
class file : -
namespace worker { public class processingwork { public void testtimer() { datatable workcheck = getnewwork(); // new work database if there foreach (datarow dr in workcheck.rows) { if (dr["isnew"] == "true") { timer jobtimer = new timer(timer => { try { console.writeline("id " + convert.toint32(dr["workid"]).tostring()); int workid = convert.toint32(dr["workid"]); if (workid != 0) { console.writeline(datetime.now + " | running " + workid); ((timer)timer).change(timespan.fromseconds(2), timespan.fromseconds(999)); } } catch (exception ex) { //log } }); jobtimer.change(0, 0); } } } } }
program main : -
class program { static void main(string[] args) { thread[] workerthread = new thread[1]; processingwork pw = new processingwork(); workerthread[0] = new thread(() => { int = 0; while (true) { console.writeline("running " + i); pw.testtimer(); thread.sleep(10000); i++; } }) { name = "test" }; workerthread[0].start(); }
my objective of code allow each time keep on repeat. when call again function thread run , call pw.testimer()
check on database new work need process . if there create timer work .
problem facing when call again pw.testtimer();
running timer stop , gone . try without re-call pw.testtimer();
time run every 2 second have set .
what need create timer should continue run , , when there new work , add on timer .
the problem not because of timer behaviour , problem because of whenever workcheck
table got edit , timer created before not able reference value , therefore timer abort.
e.g in running timer convert.toint32(dr["workid"]); //value 1
, because update table datatable workcheck = getnewwork();
when there no new data come row empty, rewrite table, first timer referencing value 1 , value 0. therefore causes running timer abort.
i fixed deep cloning workcheck , timer should reference cloning table
from
foreach (datarow dr in gjoblist.rows)
to
foreach (datarow dr in gjoblist.deepclone().rows)
thanks helping .
Comments
Post a Comment