2013-08-23 33 views
0

我創建了一個簡單的工具,可以找到網站中的註冊選項(200網站列表是arraylist)。 我使用webbrowser,但它有一個緩存和cookie的問題,所以我切換到webclient。它工作正常,當我把斷點和調試,但是當我正常運行,它還包括那些沒有註冊選項的網站。 這裏是我的代碼C#Webclient無法正常工作

private void btnSearch_Click(object sender, EventArgs e) 
    {   
      timer1.Enabled = true; 
      timer1.Start(); 
    } 

定時器1碼

string st; 
     private void timer1_Tick(object sender, EventArgs e) 
     { 
       st = ""; 
Application.DoEvents();     
         try 
         { 
          st = lst[dataindex2].ToString();  
          using (WebClient asyncWebRequest = new WebClient()) 
          { 
           asyncWebRequest.DownloadDataCompleted += asyncWebRequest_DownloadDataCompleted; 
           Uri urlToRequest = new Uri(st); 
           asyncWebRequest.DownloadDataAsync(urlToRequest); 
           asyncWebRequest.Dispose(); 
          } 

          dataindex2++; 
          if (dataindex2 == lst.Count) 
          { 
           timer1.Stop();         
           lblStatus.Text = "Stopped"; 
           lblStatus.ForeColor = Color.DarkRed; 
           MessageBox.Show("Search Completed");         
          } 
         } 
         catch (Exception ex) 
         { 
          timer1.Stop();        
          lblStatus.Text = "Stopped"; 
          lblStatus.ForeColor = Color.DarkRed; 
          timer1.Dispose(); 
          MessageBox.Show(ex.Message); 
          return; 
         } 

asyncWebRequest_DownloadDataCompleted代碼:

private void asyncWebRequest_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) 
    { 
     if (e.Error != null) 
     { 
      timer1.Stop(); 
      ena(); 
      lblStatus.Text = "Stopped"; 
      lblStatus.ForeColor = Color.DarkRed; 
      timer1.Dispose();     
      MessageBox.Show(e.Error.Message);     
     } 

     if (e.Result != null && e.Result.Length > 0) 
     { 
      string browsetext = ""; 
      int = iSuccess = 0; 
      browsetext = Encoding.Default.GetString(e.Result); 

        iSuccess = browsetext.IndexOf("Sign up") + 1; 
        if (iSuccess == 0) 
        { 

        } 
        else 
        { 

         listBox1.Items.Add(st); 
         domaincount++;        
         lblDomainCount.ForeColor = Color.DarkGreen; 
         lblDomainCount.Text = domaincount.ToString(); 
        } 
       } 
       else 
       { 
       } 
      } 
     } 
     else 
     { 
      MessageBox.Show("No data found."); 
     } 
    } 

請幫助,如果有WebClient的不掛然後GUI的任何替代請建議。 TY。

回答

0

您在開始下載時立即處置WebClient。

asyncWebRequest.DownloadDataAsync(urlToRequest); 
asyncWebRequest.Dispose(); 

請幫助,如果有不掛Web客戶端的任何備用GUI

看到my other answer這對於Web客戶端創建一個包裝器,能夠使用異步/ AWAIT 。 HttpClient也可以替代。

+0

所以我不應該處置它?只有在下載完成後,才能使用 – Noobish

+1

@ user1445345。 – I4V