Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement synchronization with timers in C#
    primarykey
    data
    text
    <p>I have a scenario where my C# class has two methods say <code>DoThis()</code> and <code>DoThat()</code> 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:</p> <ul> <li>After a call to <code>DoThis()</code>, wait at least <code>t1</code> seconds before proceeding with <code>DoThat()</code> execution</li> <li>After a call to <code>DoThat()</code>, wait at least <code>t2</code> seconds before proceeding with <code>DoThis()</code> execution</li> </ul> <p>So essentially in pseudocode:</p> <pre><code>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); } </code></pre> <p><code>DoStuff()</code> and <code>DoOtherStuff()</code> are <b>not</b> long-running methods and do not share resources otherwise. Typically <code>DoThis()</code> and <code>DoThat()</code> will not be called concurrently. But I still need to protect against potential deadlocks. </p> <p>How can I best implement <code>DoThis()</code>, <code>DoThat()</code> in C#? </p> <p><b>EDIT</b> 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().</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload