multithreading - How to use signalling mechanism for performing intensive work (that do not overlap) with a thread and manualresetevent in C#? -
i have existing application 1 thread running intensive work in background every numofminutesinterval
. done using thread.sleep
(sleeping entire interval period) i've read thread.sleep evil , it's sloppy design, wanna alter signalling mechanism. below code wrote (using dispatcher timer wpf, think in little scenario it's same winforms timer well).
the dispatcher (running in ui thread) ticks every second, , within tick function checks whether interval has passed, , if so, signal manualresetevent set()
. i'm wondering if bad design if intensive work extends pass interval period? if set numofminutesinterval = 1
, work took 1 min , 1 second, mean we'll skip 1 set()
call, since tick attempting set()
event while work still beingness done , worker thread not yet blocking.
please notice i've set lastworkdonetime = datetime.now;
after calling set()
, should move worker thread instead (calling lastworkdonetime = datetime.now;
before manualresetevent.waitone();
)?
if bad design, should alter it? reading!
//thread work done here private void mydowork_threadstart() { while(flagapplicationstillrunning == true) { //do intensive work here manualresetevent.waitone(); } } // tick every sec private int numofminutesinterval = 1; private datetime lastworkdonetime = datetime.now; private void dispatchertimer_tick(object sender, eventargs e) { if((datetime.now - lastworkdonetime).minutes > numofminutesinterval) { manualresetevent.set(); lastworkdonetime = datetime.now; } }
you start task , have perform intensive work.
private void dispatchertimer_tick(object sender, eventargs e) { if ((datetime.now - lastworkdonetime).minutes > numofminutesinterval) { task.factory.startnew(dointensivework()); lastworkdonetime = datetime.now; } }
as far setting lastworkdonetime
you. if set in fires off task, have possibility of 2 or more tasks running @ same time performing work. if set @ end of function performing work introduce delay based on how long takes finish work.
i using 1 of timer objects , allow handle timing instead of using dispatchertimer_tick
event. there system.timers.timer
, system.threading.timers
, , others.
to help determine timer alternative work best you: comparing timer classes in .net framework class library
c# multithreading
No comments:
Post a Comment