在ContinueWith(anotherTask)+ C#任务并行库中共享变量

Sat*_*h K 3 c# task-parallel-library

我使用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
    });
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 6

是的,它会奏效.然而,使用StopWatch该类应该更好,因为这是一种更准确和有效的方法来计算方法的经过时间,处理机器上运行的任何东西.有关后一个论点的更多信息,请看这里:

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
}
Run Code Online (Sandbox Code Playgroud)