Async Await和ContinueWith没有按预期工作

Bla*_*ski 2 c# asynchronous .net-core continuewith

我有以下代码在.NET Standard 2.0上运行:

public static Task<JobResult> TryRunAsync(this IJob job,
                                          CancellationToken cancellationToken = default(CancellationToken))
{
    return job.RunAsync(cancellationToken)
        .ContinueWith(t => {
             if (t.IsFaulted)
                 return JobResult.FromException(t.Exception.InnerException);
             if (t.IsCanceled)
                 return JobResult.Cancelled;

             return t.Result;
         });
}
Run Code Online (Sandbox Code Playgroud)

我们注意到它没有按预期运行.我们认为当你等待对TryRun的调用时,它总是会调用可以处理异常/取消并返回作业结果的延续.我们希望减少创建的异步状态机的数量......然而,事实并非如此,它只会爆炸.这是一个较小的示例(创建一个新的.net核心2.0控制台应用程序并粘贴以下内容:

using System;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    public class Program
    {
        public static async Task Main()
        {
            // works
            await DoStuff();
            Console.ReadKey();

            // blows up
            await TryRun();
            Console.ReadKey();
        }

        public static Task DoStuff()
        {
            return Method()
                .ContinueWith(t => Throws())
                .ContinueWith(t => {
                    if (t.IsFaulted)
                        Console.WriteLine("Faulted");
                    else if (t.IsCompletedSuccessfully)
                        Console.WriteLine("Success");
                });
        }

        public static Task Method()
        {
            Console.WriteLine("Method");
            return Task.CompletedTask;
        }

        public static Task TryRun()
        {
            return Throws()
                .ContinueWith(t => {
                    if (t.IsFaulted)
                        Console.WriteLine("Faulted");
                    else if (t.IsCompletedSuccessfully)
                        Console.WriteLine("Success");
                });
        }

        public static Task Throws()
        {
            Console.WriteLine("Throws");
            throw new ApplicationException("Grr");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要<LangVersion>Latest</LangVersion>在您的csproj中.

UPDATE

我们最终使用以下代码:

public static Task<JobResult> TryRunAsync(this IJob job, 
                                           CancellationToken cancellationToken = default(CancellationToken))
{
    var tcs = new TaskCompletionSource<JobResult>(null);
    try {
        var task = job.RunAsync(cancellationToken);
        task.ContinueWith((task2, state2) => {
            var tcs2 = (TaskCompletionSource<object>)state2;
            if (task2.IsCanceled) {
                tcs2.SetResult(JobResult.Cancelled);
            } else if (task2.IsFaulted) {
                tcs2.SetResult(JobResult.FromException(task2.Exception));
            } else {
                tcs2.SetResult(JobResult.Success);
            }
        }, tcs, cancellationToken);
    } catch (Exception ex) {
        tcs.SetResult(JobResult.FromException(ex));
    }

    return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 6

抛出的方法实际上是在调用时抛出异常,而不是返回故障Task.没有Task你可以添加延续; 它甚至在到达ContinueWith呼叫之前就会上调呼叫堆栈.