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

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

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

For example, I have already written some asynchronous function and want to call it on button click. Like this:

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

And I want to call it when I click this button:

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

In google or youtube I found material only about lamda expressions. So, how to do this?

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

You can make your click handler async and then call ParseSth from there with an await. Just know that any exception thrown by your method won’t’ be caught because you’re adding async to a void method.

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

Another solution with some MVVM frameworks could be to bind an async command to your button click.