Blazor difference between a lambda callback or a direct callback

Viewed 395

So I was experimenting with Blazor and I'd like to understand the difference between these two.

<p @onclick="OnClickCallback">Click me normal</p>

<p @onclick="async () => await OnClickCallback()">Click me lambda</p>

@code {

  private async Task OnClickCallback()
  {
    await Task.Delay(500);
  }

}

What is the difference between these two approaches. What happens behind the scenes. I've found some issues with EF Core (which is a whole other topic) where the lambda approach did not throw an exception, and the normal did.

2 Answers

What is the difference between these two approaches

It adds another function, which means it introduces another call on the stack.

Also, because this is an async lambda, it allocates another Task instance.

This being said, using the former will have a negligible performance benefit.


For completeness, there is a third alternative that would prevent another Task being used, but would still result in another function call:

() => OnClickCallback()

In Blazor, that's a very good question. I don't really know if they compile differently, but I wanted to mention something that's quite important: a lambda method can pass a variable other than the normal event variables that go with the event. It's very useful to do something like this:

@foreach (var item in SomeCustomList)
    {
        <p @onclick="async (e) => await OnClickCallback(e, item )">Click me lambda</p>
    }
Related