浏览器自动化的一些体会11 webclient的异步操作

2021-04-27 02:27

阅读:674

标签:obj   运行   vat   +=   问题   har   异步执行   操作   star   

原来的代码大致如下:

     private void foo(string url)
     {
            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += (obj, ev) =>
                {
                    client.CancelAsync();
                };
                
                client.DownloadStringCompleted += (obj, ev) =>
                {
                     ................
                     Thread.Sleep(30000);
                     bar(client, newUrl);
                }
            }
     }

     private void bar(WebClient client, string url)
     {

           client.DownloadStringAsync(url);
     }

  

本来以为这样可以自动访问一串网址(这里省略了取下一个url的代码),但运行后发现,经常会运行到一半停下来,程序并没有死掉,只是停止了,不继续访问下一个网址。

开始以为是Thread.Sleep()在做怪,把它移到bar方法里:

     private void bar(WebClient client, string url)
     {
           Thread.Sleep(30000);
           client.DownloadStringAsync(url);
     }

结果没用。想了半天,最后估计是访问某个网址时,一直在请求,但一直没收到数据,所以没有触发DownloadProgressChanged 事件。又因为是异步执行,所以UI没有阻塞。

最后用了个Timer控件,把代码改成:

     private void foo(string url)
     {
            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += (obj, ev) =>
                {
                    client.CancelAsync();
                };
                
                client.DownloadStringCompleted += (obj, ev) =>
                {
                     ................
                     if (timer1.Enabled) 
                     {
                         timer1.Stop();
                     }
                     bar(client, newUrl);
                } 
                timer1.Tick += (obj, ev) => {
                     timer1.Stop();
                     if (client.IsBusy)
                     {
                         client.CancelAsync();
                     }
                     else
                     {
                         bar(client, url);
                     }
                }
                bar(client, url);
            }
     }

     private void bar(WebClient client, string url)
     {
           Thread.Sleep(30000);
           client.DownloadStringAsync(url);
           timer1.Stop();
           timer1.Start();
     }

  

Timer的间隔也设成30秒。测试了几百个url没有问题。

浏览器自动化的一些体会11 webclient的异步操作

标签:obj   运行   vat   +=   问题   har   异步执行   操作   star   

原文地址:https://www.cnblogs.com/badnumber/p/12216522.html


评论


亲,登录后才可以留言!