使用这样的while循环是不好的做法吗?也许最好使用秒表,或者这个解决方案有一些陷阱?
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));
}
Run Code Online (Sandbox Code Playgroud)
我看到这篇文章实现了C#Generic Timeout,但是在简单的场景中使用它太复杂了 - 你需要考虑线程的同步,是否适合中止它们等等.
Jim*_*hel 16
据我了解,你希望你的方法做完一些工作,直到它完成或直到一段时间过去?我会使用a Stopwatch,并检查循环中的已用时间:
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.
}
Run Code Online (Sandbox Code Playgroud)