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

标签 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
    });
}

最佳答案

是的,它会起作用。然而,最好使用 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
}

关于c# - 在 ContinueWith(anotherTask) + C# 任务并行库中共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555972/

相关文章:

c# - 如何在没有表单的情况下捕获屏幕?

c#相对路径

c# - 带有 Parallel.For() 的 AccessViolationException

c# - 为什么Task Parallel Library在某些情况下调度任务会出现 'hidden' 1秒超时?

c# - 解析和更改数字的脚本

c# - unity计算相对于主摄像头的四元数

c# - 如何加载ascx文件中的资源 key ?

c# - SingleProducerConstrained 和 MaxDegreeOfParallelism

c# - 延迟任务开始的正确方法

c# - 更改 IQueryable 的 DataContext