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.
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.
}
It is better to use the System.Timers.Timer class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With