I have a scenario where my C# class has two methods say DoThis() and DoThat() that are called independent of each other, in any order, by an external caller. The two methods need to be synchronized in the following way:
- After a call to
DoThis(), wait at leastt1seconds before proceeding withDoThat()execution - After a call to
DoThat(), wait at leastt2seconds before proceeding withDoThis()execution
So essentially in pseudocode:
static SomeCustomTimer Ta, Tb;
static TimeSpan t1, t2;
public static void DoThis()
{
if(Tb.IsRunning())
Tb.WaitForExpiry();
DoStuff();
Ta.Start(t1);
}
public static void DoThat()
{
if(Ta.IsRunning())
Ta.WaitForExpiry();
DoOtherStuff();
Tb.Start(t2);
}
DoStuff() and DoOtherStuff() are not long-running methods and do not share resources otherwise. Typically DoThis() and DoThat() will not be called concurrently. But I still need to protect against potential deadlocks.
How can I best implement DoThis(), DoThat() in C#?
EDIT
My scenario right now is simple in that there aren’t an arbitrary number of threads calling these functions. For purpose of simplification, there’s a single caller thread calling these functions in an arbitrary sequence. So the two methods will not be called concurrently, instead the caller will call these methods one-by-one in any order. I don’t have control over the caller thread’s code so I want to enforce the delay between successive calls to DoThis(), DoThat().
This is pretty easy to solve with a timed latch. A latch is synchronization mechanism that is either opened or closed. When open threads are allowed to pass through. When closed threads cannot get through. A timed latch is one that will automatically reopen or reclose after a certain amount of time has elapsed. In this case we want a “normally opened” latch so the behavior is biased towards staying open. That means the latch will reopen automatically after the timeout, but close only if
Closeis explicitly called. Multiple calls toClosewill reset the timer.And we can implement our timed latch like the following.