首页 > 解决方案 > 如何在 Xamarin.Android 中的按钮上调用异步非 lambda 函数

问题描述

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

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

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

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

在 google 或 youtube 中,我只找到了关于 lamda 表达式的材料。那么,如何做到这一点呢?

标签: c#.netxamarinmobile-development

解决方案


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

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

一些 MVVM 框架的另一个解决方案可能是将异步命令绑定到您的按钮单击。


推荐阅读