Z.Kirik
Z.Kirik

Reputation: 121

Return values from asynchronous function Xamarin

I develop mobile application with Xamarin

What I need to do to print the data I get from the web service

Json Formated

Async function

public async Task<List<MesajModel>> MesajAl()
{
    MesajModel obj =new MesajModel();
    List<MesajModel> mesaj =new List<MesajModel>();

    string url = "https://jsonplaceholder.typicode.com/posts/1";

    try
    {
        HttpClient cl = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

        HttpResponseMessage response = await cl.SendAsync(request);

        HttpContent content = response.Content;

        var statusCode = response.StatusCode;

        string json = await content.ReadAsStringAsync();
        obj.Aciklama = json.ToString();
        obj.Mesaj = "Yaptik";
        mesaj.Add(obj);
        return mesaj;
    }
    catch (Exception e)
    {
        return mesaj;
    }
}

The function I want to trigger Xamarin.Form Event for Button Clicked

private void Button_Clicked(object sender, EventArgs e)
{
    var a=con.MesajAl().Wait();
}

Upvotes: 0

Views: 1212

Answers (2)

ashveli
ashveli

Reputation: 288

You simply have to call the method using await.

Here is a good reference for async/await operations from msdn.

async

await

Upvotes: 0

MilanG
MilanG

Reputation: 2604

Button click event should be written as:

private async void Button_Clicked(object sender, EventArgs e)
{
   var a = await con.MesajAl();
}

Use await to wait for the response and make event async.

Upvotes: 4

Related Questions