如何在 Xamarin.Android 中的按钮上调用异步非 lambda 函数

How to call an async non-lambda function on button in Xamarin.Android

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

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

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

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

在 google 或 youtube 中,我发现 material 仅关于 lamda 表达式。那么,如何做到这一点?

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

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

使用某些 MVVM 框架的另一种解决方案可能是将异步命令绑定到您的按钮点击。