Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between regular and Async methods (OnGet vs OnGetAsync)

I started learning how Razor Pages work, tutorials mention OnGet and OnPost, and also mention that we have async options too: OnGetAsync and OnPostAsync. But they don't mention how they work, obviously they're asynchronous, but how? do they use AJAX?

public void OnGet()
{
}


public async Task OnGetAsync()
{
}
like image 511
marcos.borunda Avatar asked Oct 19 '18 15:10

marcos.borunda


1 Answers

There is no actual difference between OnGet and OnGetAsync. OnGetAsync is just a naming convention for methods that contain asynchronous code that should be executed when a GET request is made. You can omit the Async suffix but still make the method asynchronous:

public async Task OnGet()
{
    ...
    await ....
    ...
}

Asynchronous methods are ones that free up their threads while they are executing so that it can be used for something else until the result of the execution is available. You can read more about how asynchronous methods work here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/#BKMK_WhatHappensUnderstandinganAsyncMethod

You can't have an Onget and an OnGetAsync handler in the same Razor Page. The framework sees them as being the same.

like image 78
Mike Brind Avatar answered Oct 24 '22 00:10

Mike Brind