How to synchronously call an asynchronous method in Windows Phone 8

We have an existing iOS app developed using Xamarin.Forms. Now we want to extend both Android and Windows Phone. In an existing application, all web service calls are made synchronously. Windows Phone only supports asynchronous calling, so we thought of asynchronous calls synchronously.

We are using the HttpClient.PostAsync method to access the service. As soon as the execution hits the PostAsync method, the phone hangs. The code for calling the service looks like this:

private static async void CallService(System.Uri uri)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Host = uri.Host;
        client.Timeout = System.TimeSpan.FromSeconds(30);
        HttpContent content = new StringContent("", Encoding.UTF8, "application/xml");

        var configuredClient = client.PostAsync(uri, content).ConfigureAwait(false);
        var resp = configuredClient.GetAwaiter().GetResult();
        resp.EnsureSuccessStatusCode();
        responseString = resp.StatusCode.ToString();
        resp.Dispose();

        client.CancelPendingRequests();
        client.Dispose();
    }
}

      

I know this is due to blocking of the UI thread, so only I implemented ConfigureAwait (false), but it didn't work at all. I tried using System.Net.WebClient but same result.

Now, how do I make this asynchronous call to a synchronous process in Windows Phone 8?

+3


source to share


1 answer


First of all, avoid using async void methods because you can't easily wait for it to complete. Return Task

instead, while inside a method async

, you don't need to do anything special to return Task

. The compiler does all the work for you.

You need to wait for a call HttpClient.PostAsync

, which should be enough to keep the UI alive.



private static async Task CallService(System.Uri uri)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Host = uri.Host;
        client.Timeout = System.TimeSpan.FromSeconds(30);
        HttpContent content = new StringContent("", Encoding.UTF8, "application/xml");

        var resp = await client.PostAsync(uri, content);// Await it
        resp.EnsureSuccessStatusCode();
        responseString = resp.StatusCode.ToString();
        resp.Dispose();

        client.CancelPendingRequests();
    }
}

      

Note. I uninstalled ConfigureAwait(false)

as not required. If you really need it, you can add it back.

+5


source







All Articles