【发布时间】:2018-02-21 05:55:02
【问题描述】:
我有一个我不等待的任务,因为我希望它在后台继续自己的逻辑。该逻辑的一部分是延迟 60 秒并重新检查以查看是否需要完成一些分钟的工作。缩写代码如下所示:
public Dictionary<string, Task> taskQueue = new Dictionary<string, Task>();
// Entry point
public void DoMainWork(string workId, XmlDocument workInstructions){
// A work task (i.e. "workInstructions") is actually a plugin which might use its own tasks internally or any other logic it sees fit.
var workTask = Task.Factory.StartNew(() => {
// Main work code that interprets workInstructions
// .........
// .........
// etc.
}, TaskCreationOptions.LongRunning);
// Add the work task to the queue of currently running tasks
taskQueue.Add(workId, workTask);
// Delay a period of time and then see if we need to extend our timeout for doing main work code
this.QueueCheckinOnWorkTask(workId); // Note the non-awaited task
}
private async Task QueueCheckinOnWorkTask(string workId){
DateTime startTime = DateTime.Now;
// Delay 60 seconds
await Task.Delay(60 * 1000).ConfigureAwait(false);
// Find out how long Task.Delay delayed for.
TimeSpan duration = DateTime.Now - startTime; // THIS SOMETIMES DENOTES TIMES MUCH LARGER THAN EXPECTED, I.E. 80+ SECONDS VS. 60
if(!taskQueue.ContainsKey(workId)){
// Do something based on work being complete
}else{
// Work is not complete, inform outside source we're still working
QueueCheckinOnWorkTask(workId); // Note the non-awaited task
}
}
请记住,这是示例代码,只是为了展示我的实际程序的极简版本。
我的问题是 Task.Delay() 延迟的时间超过了指定的时间。有些东西阻止了这种情况在合理的时间范围内继续进行。
不幸的是,我无法在我的开发机器上复制该问题,而且它每隔几天才会在服务器上发生一次。最后,它似乎与我们一次运行的工作任务的数量有关。
什么会导致延迟时间超过预期?此外,如何调试这种情况?
这是对我的另一个未得到答复的问题的跟进:await Task.Delay() delaying for longer that expected
【问题讨论】:
标签: c# .net async-await