Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a thread doesn't work when I use ToListAsync method

I have an EF Core program.

Code

class EagerLoading
{
    public async void load()
    {
        Console.WriteLine("a");
        var teams = await loadTeamsAsync();
        Console.WriteLine("c");
    }
    public async Task<List<Team>> loadTeamsAsync()
    {
        Console.WriteLine("b");
        using (var context = new SchoolContext())
        {
            return await context.teams.
                ToListAsync();
        }
    }
}
//Entry method
static void Main(string[] args)
{
    new EagerLoading().load();
}

Output

a
b

Expected

a
b
c

Question

where am I wrong? why the Console.WriteLine("c"); doesn't execute?

like image 754
David Avatar asked May 15 '26 18:05

David


1 Answers

You will need to put a ReadKey or similar in the Main method to stop the application from exiting.

Load is an async void (which should be ringing alarm bells) and runs unobserved, in-turn there is a high probability of the application exiting before it finishes in the way you expect (or in this case writing to the console).

static void Main(string[] args)
{
    new EagerLoading().load();
    Console.ReadKey();
}

Note : You should only ever be using on async voids on event handlers (or constructs that logically represent event handlers), it's more-or-less the primary reason they exist.

like image 101
TheGeneral Avatar answered May 18 '26 09:05

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!