WP8 SDK import Service Reference with task-based o

2020-03-26 08:25发布

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条回答
贼婆χ
2楼-- · 2020-03-26 08:46

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/"));
}
查看更多
登录 后发表回答