Warm tip: This article is reproduced from serverfault.com, please click

c#-如何在Xamarin.Android中的按钮上调用异步非Lambda函数

(c# - How to call an async non-lambda function on button in Xamarin.Android)

发布于 2020-11-28 07:49:16

例如,我已经编写了一些异步函数,并希望在单击按钮时调用它。像这样:

static async Task<string> ParseSth(string URL) { ... }

当我单击此按钮时,我想调用它:

FindViewById<Button>(Resource.Id.ButtonParse).Click += ...

在google或youtube中,我发现仅关于lamda表达式的材料。那么,该怎么做呢?

Questioner
Александр II
Viewed
12
Cem.S 2020-11-28 16:36:40

你可以使你的点击处理程序异步,然后在等待状态下从那里调用ParseSth。只是知道你的方法抛出的任何异常都不会被捕获,因为你正在向void方法添加异步。

private async void button_Click(object sender, EventArgs e)
{
    await ParseSth(myTextBox.Text); // Any exception thrown here will be lost
}

某些MVVM框架的另一种解决方案是将异步命令绑定到你的按钮单击。