WP8任务<string> DownloadString </string>

时间:2014-02-12 09:52:45

标签: c# .net json web-services windows-phone-8

我想使用此类从其余Web服务下载JSON数据:

public static class Extensions
    {
        public static Task<string> DownloadStringTask(Uri uri)
        {
            WebClient webClient = new WebClient();
            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;
        }
    }

但我不知道怎么称呼这个功能。

是否还有其他函数用于下载JSON数据?

2 个答案:

答案 0 :(得分:2)

可以这么简单:

var uri = new Uri("example.org");
var dl = Extensions.DownloadStringAsync(uri); -- starts download
// .. do something in the meantime
Console.WriteLine(dl.Result); --- wait for the download to complete

您还可以使用asyncawait c#关键字:

public static async void DoDownload() 
{
     var uri = new Uri("example.org");
     Console.WriteLine(await Extensions.DownloadStringAsync(uri));            
}

答案 1 :(得分:0)

这样称呼:

它看起来像是一种扩展方法,但不是。

Task<string> t = Extensions.DownloadStringTask(new Uri("http://foo.com"));
string s = t.Result;