0

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.

6
  • 2
    Create a class that implements IDisposable. Do the lock creation in the constructor of that class and the Release in Dispose along the measuring code for the aquiring time. Then you can use a somewhat standard using syntax. using(new MyLovelyLock()) { /*do work*/ } Commented Jul 11, 2023 at 16:57
  • Out of curiosity, how is the "last time this lock was acquired" information useful? How are you planning to use this information? Btw be aware that casually reading the lastTimeLockAcquired without using the _lock could result in a torn read on 32 bit machines. Commented Jul 11, 2023 at 23:00
  • 1
    Ah, I see. Personally I would do it differently. I would instantiate a System.Threading.Timer, and I would call .Change(15000, 15000) after each SendData1/SendData2 operation. This way a request will be sent after 15 sec of inactivity. The Change method is thread-safe. Commented Jul 12, 2023 at 4:46
  • 1
    Thanks @TheodorZoulias. I am personally using System.Timers.Timer so I looked up the equivalent of Change() and the best answer I could find was to call Stop() and Start() on this question. WIll be club this a Restart() method and will use this as for now Commented Jul 12, 2023 at 6:25
  • 1
    Personally I am not a fan of the System.Timers.Timer component. It's not a well designed component IMHO. You can read my arguments at the bottom of this answer. Commented Jul 12, 2023 at 6:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.