Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement c# timeout

Tags:

c#

.net

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.

like image 876
Andriy Kizym Avatar asked Feb 16 '11 16:02

Andriy Kizym


2 Answers

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.
}
like image 189
Jim Mischel Avatar answered Oct 31 '22 13:10

Jim Mischel


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

like image 44
John Pick Avatar answered Oct 31 '22 12:10

John Pick