【问题标题】:WP8 Task<string> DownloadStringWP8 任务<字符串> 下载字符串
【发布时间】:2014-02-12 09:52:44
【问题描述】:

我想用这个类从 rest WebServices 下载 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 数据的函数吗?

【问题讨论】:

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


【解决方案1】:

可以这么简单:

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

【讨论】:

    【解决方案2】:

    这样称呼它:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-13
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2014-01-12
      相关资源
      最近更新 更多