Task.ContinueWith的替代方案

时间:2014-12-22 10:46:33

标签: c# .net task-parallel-library async-await

我在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;
}

我多次看到避免ContinueWith的建议,而是使用await。你能帮帮我吗?

1 个答案:

答案 0 :(得分:4)

这很简单。您需要在方法中使用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;
}