[英]Implement c# timeout
使用这样的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));
}
我看到这篇文章实现了C#Generic Timeout ,但是在简单的场景中使用它太复杂了 - 你需要考虑线程的同步,是否适合中止它们等等。
据我了解,你希望你的方法做完一些工作,直到它完成或直到一段时间过去? 我会使用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.
}
最好使用System.Timers.Timer类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.