无法使用基于任务的操作导入服务参考

无法使用基于任务的操作导入服务参考

本文介绍了WP8 SDK 无法使用基于任务的操作导入服务参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,在 VS2012 中使用生成基于任务的操作"导入服务引用似乎不起作用.它变灰了.

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

针对 WPF 的新项目进行的测试工作正常 - 我可以选择基于任务或异步操作.

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?

推荐答案

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;
    }
}

用法:

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

这篇关于WP8 SDK 无法使用基于任务的操作导入服务参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:45