DownloadStringAsync wait for request completion

前端 未结 6 1376
感动是毒
感动是毒 2020-12-10 13:41

I am using this code to retrieve an url content:

private ArrayList request(string query)
{
    ArrayList parsed_output = new ArrayList();

    string url = s         


        
6条回答
  •  隐瞒了意图╮
    2020-12-10 14:04

    this will keep your gui responsive, and is easier to understand IMO:

    public static async Task DownloadStringAsync(Uri uri, int timeOut = 60000)
    {
        string output = null;
        bool cancelledOrError = false;
        using (var client = new WebClient())
        {
            client.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error != null || e.Cancelled)
                {
                    cancelledOrError = true;
                }
                else
                {
                    output = e.Result;
                }
            };
            client.DownloadStringAsync(uri);
            var n = DateTime.Now;
            while (output == null && !cancelledOrError && DateTime.Now.Subtract(n).TotalMilliseconds < timeOut)
            {
                await Task.Delay(100); // wait for respsonse
            }
        }
        return output;
    }
    

提交回复
热议问题