[英]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.