Home > Enterprise >  How to await for an PostAsync method in xamarin?
How to await for an PostAsync method in xamarin?

Time:12-29

I am trying to do something like await client.PostAsync() in a xamarin project, but it does not waits. How can I make it wait ? The same code in winforms project does waits.

my code

private bool ConfirmLogin(string user, string password)
{
    bool result = false;

    AppLoginRequest appLoginRequest = new AppLoginRequest();
    AppLoginResponse appLoginResponse = new AppLoginResponse();

    // step 1
    Task<HttpResponseMessage> task = GetAppLogin(appLoginRequest, appLoginResponse);

    // step 4
    result = appLoginResponse.Authorized;

    return result;
}

and the code for GetAppLogin

private async Task<HttpResponseMessage> GetAppLogin(AppLoginRequest appLoginRequest, AppLoginResponse appLoginResponse)
{
    HttpResponseMessage response = null;

    string JsonData = JsonConvert.SerializeObject(appLoginRequest);
    System.Net.Http.StringContent restContent = new StringContent(JsonData, Encoding.UTF8, "application/json");
    HttpClient client = new HttpClient();
    try
    {
        // step 2
        response = await client.PostAsync(@"http://x.x.x.x:xxxx/api/XXX/GetAppLogin", restContent);

        // step 3
        if (response.IsSuccessStatusCode)
        {
            var stream = await response.Content.ReadAsStringAsync();
            AppLoginResponse Result = JsonConvert.DeserializeObject<AppLoginResponse>(stream);
        }
        else
        {
            appLoginResponse.Remark = response.ReasonPhrase;
        }
    }
    catch (Exception ex)
    {
        appLoginResponse.Authorized = false;
        appLoginResponse.Remark = ex.Message;
    }

    return response;
}

What I need is to execute the steps (// step x in the comments of the code) in the correct sequential order.

Step 1, then step 2, then step 3 and finally step 4

But it executes like this

step 1 then step 2 and then step 4 and step 3

This off course messes up the complete logic, is there a way I can force the client.PostAsync to actually really wait ?

I found hundreds of questions on how to run an async task synchronously, but all seem to not work.
Is xamarin different about this ?
I run the exact same code from a testclient written in winforms and there it does waits.

CodePudding user response:


async void ButtonClick(...)
{
   bool x = await ConfirmLogin(..., ...);
}


private async Task<bool> ConfirmLogin(string user, string password)
{
    bool result = false;

    AppLoginRequest appLoginRequest = new AppLoginRequest();
    AppLoginResponse appLoginResponse = new AppLoginResponse();

    // step 1
    await  GetAppLogin(appLoginRequest, appLoginResponse);

    // step 4
    result = appLoginResponse.Authorized;

    return result;
}

Do not use async void when you can avoid it. It is a cop-out especially intended for eventhandlers. "To get the async going"

  • Related