Interested in reviews about my timeout class

Many areas of the project I'm working on have a simple timeout check, which basically runs the code through a try loop until 10 seconds succeed or fail.

class Timeout {
    private readonly DateTime timeoutDate;
    public bool FlagSuccess;

    public Timeout() {
        timeoutDate = DateTime.UtcNow.AddSeconds(10);
        flagSuccess = false;
    }

    public bool continueRunning() {
        if (!flagSuccess && DateTime.UtcNow < timeoutDate) return true;
        else return false;
    }
}

Here is an example of the class used:

Timeout t = new Timeout();
while (t.continueRunning()) {
    try {
        //PUT CODE HERE
        t.flagSuccess = true;
    }
    catch(Exception e) {
        Console.WriteLine(e.Message);
    }
}

Before implementing this, is there a better and more standard way to do this? What I have above is based on my blind intuition.

+3
source share
3 answers

Use .NETs Timerclass (s):

using System.Timers;

public static void Main() {
    Timer t = new Timer();
    t.Elapsed += new ElapsedEventHandler(ActionWhenFinished);
    t.Interval = 10000;
    t.Start();
}

public static void ActionWhenFinished()
{
    // cancel any action
}

Your class will Timeoutblock the current thread in which it is running, which is not the case System.Timer.

+4
source

I seem to like a busy cycle, but here's how you do it with StopWatch.

    System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
    timer.Start();
    bool complete;
    while( timer.ElapsedMilliseconds < 10000 && !complete)
    {
        //Do stuff
       // and someday... complete = true;
    }

, .

class AgingWait
{
 System.Diagnostics.Stopwatch _watch = new System.Diagnostics.Stopwatch();
 int maxMilliseconds;
 bool forceExpire;
 public bool Expired
 {
     get { return forceExpire || maxMilliseconds < _watch.ElapsedMilliseconds; }
 }
 public AgingWait(int milli)
 {
     _watch.Start();
     maxMilliseconds = milli;
 }

 public void Expire()
 {
     forceExpire = true;
 }
}

    AgingWait waiter = new AgingWait(1000);
    while (!waiter.Expired)
    {
        if (condition)
            waiter.Expire();

    }
0

I suggest changing the loop in the do-while loop, so you are guaranteed to start the loop at least once, even if your thread starts instantly between setting the timeout and starting the loop. In addition, I would suggest that it might be useful for the Timeout class to include the RemainingMilliseconds property and possibly RemainingMillisecondsUpTo (Integer N), which can be passed to various block or timeout procedures.

0
source

Source: https://habr.com/ru/post/1790797/


All Articles