我使用continuationWith(anotherTask)创建了一个任务,如下所示。我想知道第一个任务完成它的工作所需的时间。我在task1和子任务之间共享变量"task1StartedDateTime“。这样做会没有任何问题吗?
public static void MyMethod()
{
var task1StartedDateTime = DateTime.Now;
var task1 = doWorkAsync();
task1.ContinueWith(t1 => {
var task1TookTime = DateTime.Now - task1StartedDateTime;
Console.WriteLine($"Task 1 took {task1TookTime}");
//Some other work of this child task
});
}发布于 2018-02-01 13:40:10
是的,它会工作的。然而,使用StopWatch类应该更好,因为这是计算方法运行时间的一种更准确、更有效的方法,处理在机器上运行的任何东西。有关后一种说法的更多信息,请查看here
var stopwatch = StopWatch.StartNew();
var task1 = doWorkAsync();
task1.ContinueWith(t1 => {
stopwatch.Stop();
Console.WriteLine($"Task 1 took {stopwatch.EllapsedMilliseconds} ms.");
//Some other work of this child task
}发布于 2018-02-01 13:41:25
是的,您可以在lambda - captured variables中使用捕获的变量,以此方式将其提升为匿名类实例,以确保它们可以比在其中声明它们的方法更持久,并允许在外部方法和continuation之间共享。
但是,您应该使用Stopwatch来测量时间-它更准确。
在.Net 4.5和更高版本中,您还可以选择将.ContinueWith中的continuation替换为awaited continuation -这具有额外的保证,并且更易于阅读:
public static async Task MyMethod()
{
var sw = new Stopwatch();
sw.Start();
await doWorkAsync();
var task1TookTime = sw.Elapsed;
Console.WriteLine($"Task 1 took {task1TookTime}");
//Some other work of this child task
}(但请注意,如果等待MyMethod,则任务只会在doWorkAsync和计时器日志记录完成后完成,这与您的原始实现不同)。
https://stackoverflow.com/questions/48555972
复制相似问题