也许最好使用秒表,或者这个解决方案有一些陷阱?
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)); }
我看到这篇文章Implement C# Generic Timeout,
但是在简单的场景中使用它太复杂了 – 你需要考虑线程的同步,是否适当中止它们等等.@H_502_7@解决方法 据我了解,你希望你的方法做完一些工作,直到它完成或直到一段时间过去?我会使用秒表,并检查循环中的经过时间:
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.}总结
以上是内存溢出为你收集整理的实现c#timeout全部内容,希望文章能够帮你解决实现c#timeout所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)