c# - Monitor Wait for caching,... it this a good practice? -
i wrote code, , found out there issue monitor.wait, forcing me operation within locks, wanted if way keep thread waiting,....
i'm not sure if thread.join job, there lots of threads running within application, , each specific job, may terminate within time...
here code:
public static class taskmanager { private static readonly object updatelock = new object(); private static readonly object waitlock = new object(); private static readonly liaisondb _db = new liaisondb(); private static list<liaqueue> _liaqueuelist = new list<liaqueue>(); private static datetime _lastupdate = new datetime(); public static liaqueue gettask(string sessiontype) { liaqueue task; lock (updatelock) { if (_lastupdate < datetime.now.addseconds(-5)) { thread t = new thread(updatecache) {isbackground = true}; t.start(); lock (waitlock) { monitor.wait(waitlock); } _lastupdate = datetime.now; } task = _liaqueuelist .firstordefault(w => w.stat == 0 && w.type != null || string.equals(w.type, sessiontype)); } return task; } private static void updatecache() { try { _liaqueuelist = _db.liaqueue.where(w => w.stat == 0).tolist(); } { lock (waitlock) { monitor.pulse(waitlock); } } } }
as see put 2 lock, , 1 of them monitor.wait, keep thread waiting answer...
i think have returns null while cache getting refreshed?...
from msdn
if 2 threads using pulse , wait interact, result in deadlock.
so, no. implementation not best practice.
it seems me gettask supposed update cache on background thread, block calling thread until cache updated, , return first task according select criteria.
since calling thread block (wait) cache updated, don't quite understand point of using background thread in first place. if purpose prevent multiple calling threads update cache in parallel, use lock(updatelock) statement.
if want run cache on background thread anyway (and wait it), consider using task library instead. don't se point of it.
lock (updatelock) { if (_lastupdate < datetime.now.addseconds(-5)) { task.run(() => { _liaqueuelist = _db.liaqueue.where(w => w.stat == 0).tolist(); }).wait(); _lastupdate = datetime.now; } } return _liaqueuelist.firstordefault(w => w.stat == 0 && w.type != null || string.equals(w.type, sessiontype));
Comments
Post a Comment