首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在ContinueWith(anotherTask) + C#任务并行库中共享变量

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

Stack Overflow用户
提问于 2018-02-01 13:33:15
回答 2查看 504关注 0票数 3

我使用continuationWith(anotherTask)创建了一个任务,如下所示。我想知道第一个任务完成它的工作所需的时间。我在task1和子任务之间共享变量"task1StartedDateTime“。这样做会没有任何问题吗?

代码语言:javascript
复制
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
    });
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-01 13:40:10

是的,它会工作的。然而,使用StopWatch类应该更好,因为这是计算方法运行时间的一种更准确、更有效的方法,处理在机器上运行的任何东西。有关后一种说法的更多信息,请查看here

代码语言:javascript
复制
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
}
票数 6
EN

Stack Overflow用户

发布于 2018-02-01 13:41:25

是的,您可以在lambda - captured variables中使用捕获的变量,以此方式将其提升为匿名类实例,以确保它们可以比在其中声明它们的方法更持久,并允许在外部方法和continuation之间共享。

但是,您应该使用Stopwatch来测量时间-它更准确。

在.Net 4.5和更高版本中,您还可以选择将.ContinueWith中的continuation替换为awaited continuation -这具有额外的保证,并且更易于阅读:

代码语言:javascript
复制
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和计时器日志记录完成后完成,这与您的原始实现不同)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48555972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档