Nested Async Await Does not Wait

前端 未结 2 1758
忘掉有多难
忘掉有多难 2021-01-18 08:05

I think I missunderstanding the behaviour of async await in c#.

I have two methods that return a Task defined like

<         


        
相关标签:
2条回答
  • 2021-01-18 08:44

    Name1 is expecting an argument of action, but what you really want is a func. In other words, Name1 should look something like this:

    public static double Name1(Func<Task> longOperation)
    {
        longOperation().Wait();
    }
    

    Alternatively, wrap your action in a func and await it.

    public static double Name1(Action longOperation)
    {
        Func<Task> f = async () => { longOperation(); };
        f.Wait();
    }
    

    If you await an async sub, then the sub runs in the background but does not block the continuing execution of the calling method.

    If you want to execute a sub and wait for it to complete before continuing with downstream logic, then convert your async subs to async functions (with a result type of threading.tasks.task when there is no actual return value).

    This site has some great examples of common mistakes people make with async await: https://devblogs.microsoft.com/pfxteam/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/

    0 讨论(0)
  • 2021-01-18 08:54

    The Name1 method takes a delegate and returns a Task<T> where T is the type returned by the delegate. In your case, the delegate returns Task, so we get Task<Task> as the result. Using await waits only for the completion of the outer task (which immediately returns the inner task) and the inner task is then ignored.

    You can fix this by dropping the async and await in the lambda function.

    Also, take a look at Asynchronous Gotchas in C#.

    0 讨论(0)
提交回复
热议问题