Situation - there is an indefinite set of methods, and they have a boolean showing activity, for example bool Active, after a while (different for different methods), this boolean should be changed.

At the moment I solve this problem with a patch of the form

private IEnumerator SwitchFlipper ( float duration ) { var durationTimerS = Stopwatch.StartNew(); while (durationTimerS.Elapsed.TotalSeconds <= duration) { yield return null; } Active = !Active; durationTimerS.Stop(); durationTimerS.Reset(); } 

But I would like to have some one method that will receive from outside (from other methods) the duration and which variable to change to it through this time.

Is the question at all possible? (it seems to me yes, I'm just not strong in C #) If so how can this be implemented?

    1 answer 1

    Yes, easily. For example, so.

     static async void ExecuteAfter(TimeSpan s, Action a) { await Task.Delay(s); a(); } 

    and in the place where you need to change the variable:

     bool v = true; ExecuteAfter(TimeSpan.FromSeconds(5), () => v = !v); 

    Note that if you are not in a UI thread, then it would be nice to synchronize the call to a variable:

     object m = new object(); ExecuteAfter(TimeSpan.FromSeconds(5), () => { lock (m) v = !v; }); 

    If you perform actions in the current thread before the right time, then it is probably easier to use time comparisons:

     var endTime = DateTime.Now + TimeSpan.FromSeconds(5); while (DateTime.Now < endTime) { // выполнять какую-то работу } 
    • Thanks, I grabbed the general idea - astion
    • But what exactly are you in this line? ExecuteAfter (TimeSpan.FromSeconds (5), () => {lock (m) v =! V;}); do i sincerely not understand what lock is doing? - astion September
    • @astion: It does synchronization in case of multithreaded access. If the variable is accessed from multiple threads, lock is needed. - VladD