asynchronous web response windows phone 8

2019-02-27 12:40发布

This is the code I use to download an URL as html. The thing is, is there any way I can do this asynchronous? the problem I want to know whether the response is successful and what is in the response before the program continues. It would be perfect if you could await client.DownloadStringAsync and a task.delay won't always work besides I don't like that idea of setting an standard time to wait. Thank you!

        Uri uri = new Uri(url);
        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.AllowReadStreamBuffering = true;
        client.DownloadStringAsync(uri);

1条回答
干净又极端
2楼-- · 2019-02-27 13:05

There are two solutions.

The first one (which I recommend) is to use the Microsoft.Net.Http NuGet package and change your code to use the new HttpClient instead of the old WebClient:

Uri uri = new Uri(url);
HttpClient client = new HttpClient();
await client.GetStringAsync(uri);

The second solution will allow you to continue using WebClient, so it may work as a temporary fix if you have a lot of other code depending on WebClient. To use async with WebClient, install the Microsoft.Bcl.Async NuGet package, and then you can use DownloadStringTaskAsync:

Uri uri = new Uri(url);
WebClient client = new WebClient();
await client.DownloadStringTaskAsync(uri);
查看更多
登录 后发表回答