匿名方法 - 3 种不同方式 - 异步 [英] Anonymous methods - 3 different ways - async

查看:30
本文介绍了匿名方法 - 3 种不同方式 - 异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定在标题中写什么,它们可能不都是匿名方法,但这里是:

假设我们有这个异步函数:

公共异步任务删​​除(){//某物}

我正在使用 Blazor 服务器端,我对以下四种调用函数的方式感到好奇.假设它们位于 div 标签内.

  1. onclick="@Delete"

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

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

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

我不确定 1 是否是 Blazor 的新手,但它是否理解该方法是异步的?

如果需要传入参数,将使用 2 和 3,但我以前从未使用过 async-part,只在较旧的帖子中看到过.还需要说"async() =>"吗?

解决方案

在 Blazor 的早期版本中,您需要使用选项 3,因为不支持 async 函数.如果您错过了 await,Blazor 无法知道该方法已完成,因此您需要手动调用 StateHasChanged,以便在需要时重新渲染组件.

但是,现在 Blazor 确实支持异步方法,因此您可以坚持使用选项 1,但需要注意的是,您需要该方法返回 Task 而不是 void.>

所以你需要这样的东西:

公共异步任务删​​除(){//某物}

在 Blazor 中:

onclick="@Delete"

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 () =>" ?

解决方案

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"

这篇关于匿名方法 - 3 种不同方式 - 异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆