Async Await和ContinueWith没有按预期工作

问题描述 投票:2回答:2

我有运行在.NET Standard 2.0上的the following code

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;
         });
}

我们注意到它没有按预期运行。我们认为当你等待对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");
        }
    }
}

你可能需要<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;
}
c# asynchronous .net-core continuewith
2个回答
6
投票

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


0
投票

确实,这里没有创造任务。例如,如果你做了一个循环,你将保持在同一个线程和相同的堆栈。您可以通过在Throws方法中执行Task.FromException而不是抛出来查看正确的行为。至少在核心2.1中,您可能会发现异步方法与继续版本一样快,甚至更快,并且分配更少。在尝试优化状态机之前,值得检查跟踪号。此外,如果您抛出异常,您的状态机绝对是您最关注的问题。

© www.soinside.com 2019 - 2024. All rights reserved.