简体   繁体   中英

WP8 Task<string> DownloadString

I want to use this class to download JSON data from rest WebServices :

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

But i dont know how to call this function.

Is there an other function used to download JSON data ?

It can be as simple as:

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

You can also use the async and await c# keywords:

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

Call it like this:

It looks like an extension method but is not.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM