简体   繁体   English

替代Task.ContinueWith

[英]Alternative to Task.ContinueWith

I'm using the following wrapper around Task.Run to run a task and measure how long it took: 我在Task.Run周围使用以下包装器来运行任务并测量花费了多长时间:

private static Task<MyObject> RunTask(Func<MyObject> task)
{
    var watch = Stopwatch.StartNew();
    var result = Task.Run(task);
    result.ContinueWith(t =>
    {
        watch.Stop();
        t.Result.ExecutionTimeInMs = watch.ElapsedMilliseconds;
    });
    return result;
}

I've seen many times the advice to avoid ContinueWith and instead use await . 我已经看过很多次避免使用ContinueWith的建议,而是使用await Can you help me do that? 你能帮我吗?

It's rather simple. 这很简单。 You need to use the async modifier in your method and await on Task.Run : 您需要在方法中使用async修饰符,然后await Task.Run

private static async Task<MyObject> RunTask(Func<MyObject> task)
{
    var watch = Stopwatch.StartNew();

    var result = await Task.Run(task);
    watch.Stop();
    result.ExecutionTimeInMs = watch.ElapsedMilliseconds;

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM