-2

I am not sure whether this kind of problem has been asked before. I am learning asynchronous method.

JobAsync is a trivial example of asynchronous methods, Do accepts a delegate of type Action, and Main just calls the Do which in turn call JobAsync via an asynchronous lambda. See my code below for the details.

class Program
{
    static async Task JobAsync()
    {
        Console.WriteLine("Begin JobAsync");
        await Task.Delay(5000);
        Console.WriteLine("End JobAsync");
    }

    static void Do(Action a)
    {
        Console.WriteLine("Begin Do");
        a();
        Console.WriteLine("End Do");
    }

    static async Task Main()
    {
        Console.WriteLine("Begin Main");
        Do(async () => await JobAsync());
        Console.WriteLine("End Main");
    }
}

In the output below,

Begin Main

Begin Do

Begin JobAsync

End Do

End Main

The End JobAsync does not exist.

Question

What causes this phenomenon in which the End JobAsync does not exist in the output?

Any suggestions or comments are always welcome! If Do is from a third party library, how can we know that we cannot pass an asynchronous method to it?

Edit

Is the rule of thumb "Don't pass asynchronous methods as arguments of type other than Func<...,Task or Func<...,Task<...>> of non asynchronous methods?"

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

1 Answers1

1

Your async method returns a Task, so you should be using Func<Task> instead of Action. You then have to await the task.

static async Task Do(Func<Task> a)
{
    Console.WriteLine("Begin Do");
    await a();  //Notice we await the result here
    Console.WriteLine("End Do");
}
John Wu
  • 50,556
  • 8
  • 44
  • 80