Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await in Windows Phone web access APIs

Is there support for the async/await pattern in WP8?

I need to get XML from a web-based API and it looks like that WebClient or WebRequest do not support it.

Are there classes that support async/await usable for web access in the WP8 BCL? And if not, is there a library I can use?

I know it is not that hard to create wrappers to support it, but this seems like a thing that would be included in the SDK.

like image 985
Jan Kratochvil Avatar asked Nov 01 '12 08:11

Jan Kratochvil


3 Answers

Are there classes that support async/await usable for web access in the WP8 BCL?

This is a concern that has been raised during the closed beta of the WP8 SDK, so I can answer that unfortunately, no.

But as you mentioned, it is reasonably easy to make your own wrappers.

For instance:

public static class Extensions
{
    public static Task<string> DownloadStringTask(this WebClient webClient, Uri uri)
    {
        var tcs = new TaskCompletionSource<string>();

        webClient.DownloadStringCompleted += (s, e) =>
        {
            if (e.Error != null)
            {
                tcs.SetException(e.Error);
            }
            else
            {
                tcs.SetResult(e.Result);
            }
        };

        webClient.DownloadStringAsync(uri);

        return tcs.Task;
    }
}
like image 69
Kevin Gosse Avatar answered Oct 07 '22 00:10

Kevin Gosse


There is some support for WP8 in the Microsoft.Threading.Tasks.Extensions.Phone.dll provided as part of the Microsoft.Bcl.Async NuGet package described in this blog post.

In particular, it includes WebClient.DownloadStringTaskAsync.

like image 8
Stephen Cleary Avatar answered Oct 07 '22 00:10

Stephen Cleary


I had the same issue and I found this and helped me

private async Task<T> ExecuteAsync<T>(RestRequest request)
    {
        var tcs = new TaskCompletionSource<T>();
        _client.ExecuteAsync(request, resp =>
        {
            var value = JsonConvert.DeserializeObject<T>(resp.Content);
            if (value.ErrorCode > 0)
            {
                var ex = new ToodledoException(value.ErrorCode, value.ErrorDesc);
                tcs.SetException(ex);
            }
            else
                tcs.SetResult(value);
        });
        return await tcs.Task;
    }

http://www.developer.nokia.com/Community/Wiki/Asynchronous_Programming_For_Windows_Phone_8 also I found this extension helpful http://nuget.org/packages/WP8AsyncWebClient/

like image 1
Muhammad Alaa Avatar answered Oct 06 '22 23:10

Muhammad Alaa