Track
Track

Reputation: 51

Anonymous methods - 3 different ways - async

Was unsure what to write in the title, they might not all be anonymous methods, but here goes:

Say we have this async function:

public async Task Delete(){  
  //something
}

I'm using Blazor server-side and I'm curious about the following four ways of calling a function. Lets say they are inside a div tag.

  1. onclick="@Delete"

  2. onclick="@(() => Delete(id))"

  3. onclick="@(async () => await Delete(id))"

  4. onclick="@(e => Delete(person.Id))

I'm not sure if 1 is new to Blazor or not, but does it understand that the method is async or not?

2 and 3 would be used if it was needed to pass in a parameter, but I've never used the async-part before, only seen in older posts. Is it still needed to say "async () =>" ?

Upvotes: 4

Views: 3152

Answers (1)

DavidG
DavidG

Reputation: 118937

In the early versions of Blazor you were required to use option 3 because async functions weren't supported. If you missed the await there was no way for Blazor to know the method had finished so you needed to manually call StateHasChanged so the component could be re-rendered if required.

However, now Blazor does support async methods so you can stick with option 1, with the caveat that you need the method to return Task and not void.

So you need something like this:

public async Task Delete(){  
  //something
}

And in Blazor:

onclick="@Delete"

Upvotes: 10

Related Questions