I have a lock to synchronize access to Bluetooth resources which I am using in 10 different places and I want to keep track of when was the last time this lock was acquired without adding a piece of code to all the 10 places where it's being used.
Consider
private DateTime lastTimeLockAcquired; private static object _lock = new Object() Which is being used in different places like
public SendData1(){ lock(_lock){ // Do work } public sendData2(){ lock(_lock){ // Do work } My initial idea was to create functions like
private void GetLock(){ Monitor.Enter(_lock); lastTimeLockAcquired = DateTime.Now; } private void ReleaseLock(){ Monitor.Exit(_lock); } But I would prefer to create a class and move the whole lock and DateTime object to a separate place and access the lock from there if there is any clean way to do that.
using(new MyLovelyLock()) { /*do work*/ }lastTimeLockAcquiredwithout using the_lockcould result in a torn read on 32 bit machines.System.Threading.Timer, and I would call.Change(15000, 15000)after eachSendData1/SendData2operation. This way a request will be sent after 15 sec of inactivity. TheChangemethod is thread-safe.Stop()andStart()on this question. WIll be club this aRestart()method and will use this as for nowSystem.Timers.Timercomponent. It's not a well designed component IMHO. You can read my arguments at the bottom of this answer.