1

As I know, asynchronous functions return immediately. The sample code below confirms me.

static void Main(string[] args) 
{
    StartTasks2();
    Console.ReadKey();
}

private static void StartTasks2() 
{
    Console.WriteLine($"Task2 Started: {DateTime.Now:s.ffff}");
    AddPersonFake();
    Console.WriteLine($"Task2 Finished: {DateTime.Now:s.ffff}");
}

private static async void AddPersonFake() 
{
    Console.WriteLine($"AddPersonFake Started: {DateTime.Now:s.ffff}");
    await Task.Delay(2000);
    Console.WriteLine($"AddPersonFake Finished: {DateTime.Now:s.ffff}");
}

enter image description here

But this code is not working (I'm waiting for the result as above):

static void Main(string[] args) 
{
    StartTasks1();
    Console.ReadKey();
}

private static void StartTasks1() 
{
    Console.WriteLine($"Task1 Started: {DateTime.Now:s.ffff}");
    AddPerson();
    Console.WriteLine($"Task1 Finished: {DateTime.Now:s.ffff}");
}

private static async void AddPerson() 
{
    Console.WriteLine($"AddPerson Started: {DateTime.Now:s.ffff}");

    using ( TempDbContext context = new TempDbContext() ) 
    {
        context.Persons.Add(new Person());
        await context.SaveChangesAsync();
    }

    Console.WriteLine($"AddPerson Finished: {DateTime.Now:s.ffff}");
}

enter image description here

How can I return immediately from AddPerson()?

1 Answer 1

2

From what I learned here on StackOverflow yestarday, you can do it using:

private static async void AddPerson() {
    await Task.Yield();
    Console.WriteLine($"AddPerson Started: {DateTime.Now:s.ffff}");
    using ( TempDbContext context = new TempDbContext() ) {
        context.Persons.Add(new Person());
        await context.SaveChangesAsync();
    }
    Console.WriteLine($"AddPerson Finished: {DateTime.Now:s.ffff}");
}

Task.Yield() will start incompeleted Task and when awaiting it, that is the place where your asynchronous code will start.

In your original code, method AddPerson is running synchronously until it reaches the first await

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.