Reputation: 1360
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 ?
Upvotes: 0
Views: 311
Reputation: 10940
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));
}
Upvotes: 2
Reputation: 12956
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;
Upvotes: 0