如何通过Task.ContinueWith创建传递?

End*_*ono 1 c# task-parallel-library

我想在原始任务结束时处理任务,但是希望保留原始结果和类型.附加的任务仅用于记录目的,例如写入控制台等.例如:

Task.Run(() => DateTime.Now.Hour > 12 ? "Hey!" : throw new Exception())
    .ContinueWith(t =>
    {
        if (t.IsCompletedSuccessfully)
        {
            Console.WriteLine("Success");
            return t.Result;
        }
        else
        {
            Console.WriteLine("Failure");
            throw t.Exception;
        }
    });
Run Code Online (Sandbox Code Playgroud)

原始任务的类型是Task<string>.在这里我return t.Result如果任务没有遇到错误,我throw t.Exception以防任务遇到错误.看起来类型仍然存在Task<string>但不确定异常方面.

这是正确的方法吗?或者,还有更好的方法?

Sel*_*enç 5

没有理由重新抛出异常.任务将抛出AggregrateException,你可以获得InnerExceptions属性的真正异常来处理它们.

对于日志记录,您可以使用以下TaskContinuationOptions

var t = Task.Run(() => DateTime.Now.Hour > 12 ? "Hey!" : throw new Exception());

t.ContinueWith(_ => Console.WriteLine("Success"), TaskContinuationOptions.OnlyOnRanToCompletion);

t.ContinueWith(_ => Console.WriteLine("Faiure"), TaskContinuationOptions.OnlyOnFaulted);
Run Code Online (Sandbox Code Playgroud)

仅当任务成功执行到结束时才会记录成功.如果存在未处理的异常,则会记录失败.

这会分离日志记录并获取结果.所以你可以从第一个任务得到结果.