c# - How to stop thread if another thread has acquired lock on critical section? -


i have created scheduler executes piece of program in x minutes time interval. if program execution takes more time, next job should not wait current job completed. using system.timers.timer.

_scheduler = new system.timers.timer(someminutes); _scheduler.elapsed += new elapsedeventhandler(ontimedevent); _scheduler.enabled = true; _scheduler.autoreset = true;  private void ontimedevent(object source, elapsedeventargs e) {    lock(obj)    {      //critical section    } } 

if use lock, next thread waits current thread release lock. don't want behavior. if thread acquired lock object on critical section thread should exit without executing critical section

you can use monitor.

msdn:

the monitor class controls access objects granting lock object single thread. object locks provide ability restrict access block of code, commonly called critical section. while thread owns lock object, no other thread can acquire lock. can use monitor class ensure no other thread allowed access section of application code being executed lock owner, unless other thread executing code using different locked object. more please...

but might ask, "isn't c#'s lock() does?" , in ways yes. nice thing monitor can attempt lock , specify timeout wait rather blocking thread until possibly end of time or @ least until have finished reading copy of war , peace.

plus unlike mutex, monitors light-weight use! critical sections in deep plumbings of windows os.

change code from

private void ontimedevent(object source, elapsedeventargs e) {    lock(obj)    {      //critical section    } } 

...to:

object _locker = new object(); const int sometimeout=1000;  private void ontimedevent(object source, elapsedeventargs e) {     if (!monitor.tryenter(_locker, sometimeout))     {         throw new timeoutexception("oh darn");     }      try     {         // have lock     }         {         // must ensure release lock safely         monitor.exit(_locker);     }    } 

here's msdn has tryenter:

attempts, specified number of milliseconds, acquire exclusive lock on specified object - tell me more...


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -