Andriy Kizym
Andriy Kizym

Reputation: 1796

Implement c# timeout

Is it bad practice to use such while loop? Maybe it is better to use Stopwatch, or maybe this solution has some pitfalls?

    public void DoWork()
    {
        //do some preparation
        DateTime startTime = DateTime.Now;
        int rowsCount = 0;
        int finalCount = getFinalCount();
        do
        {
            Thread.Sleep(1000);
            rowsCount = getRowsCount(); // gets rows count from database, rows are added by external app.
        } while (rowsCount < finalCount && DateTime.Now - startTime < TimeSpan.FromMinutes(10));

    }

I saw this article Implement C# Generic Timeout, but it is too complex to use in simple scenarios - you need to think about sync of threads, is it proper to abort them or not and so on.

Upvotes: 7

Views: 21002

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 133975

As I understand it, you want your method to do some work until it's done or until some period of time has elapsed? I would use a Stopwatch for that, and check the elapsed time in a loop:

void DoWork()
{
    // we'll stop after 10 minutes
    TimeSpan maxDuration = TimeSpan.FromMinutes(10);
    Stopwatch sw = Stopwatch.StartNew();
    DoneWithWork = false;

    while (sw.Elapsed < maxDuration && !DoneWithWork)
    {
        // do some work
        // if all the work is completed, set DoneWithWork to True
    }

    // Either we finished the work or we ran out of time.
}

Upvotes: 16

John Pick
John Pick

Reputation: 5650

It is better to use the System.Timers.Timer class.

Upvotes: 1

Related Questions