WP8 SDK import Service Reference with task-based o

2020-03-26 08:33发布

问题:

So far it seems that importing a service reference in VS2012 with "generate task-based operations" is not working. It os greyed out.

A test with a new project for WPF is working fine - I could select either task-based or async operations.

Is there a simple way on wrapping the async call in a task?

回答1:

Is there a simple way on wrapping the async call in a task?

Example for WebClient.DownloadStringCompleted

public static class WebClientAsyncExtensions
{
    public static Task<string> DownloadStringTask(this WebClient client, Uri address)
    {
        var tcs = new TaskCompletionSource<string>();

        DownloadStringCompletedEventHandler handler = null;
        handler = (sender, e) =>
            {
                client.DownloadStringCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

        client.DownloadStringCompleted += handler;
        client.DownloadStringAsync(address);

        return tcs.Task;
    }
}

Usage:

async void DownloadExample()
{
    WebClient client = new WebClient();
    await client.DownloadStringTask(new Uri("http://http://stackoverflow.com/questions/13266079/"));
}