Nested Async Await Does not Wait

前端 未结 2 1767
忘掉有多难
忘掉有多难 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 longOperation)
    {
        longOperation().Wait();
    }
    

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

    public static double Name1(Action longOperation)
    {
        Func 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/

提交回复
热议问题