我想循環訪問一個數組並在每次迭代中執行httpwebrequest。 該代碼似乎工作,但它會暫停一段時間(例如比設置的超時時間更長,嘗試將其設置爲100來檢查並且它仍然暫停),然後繼續進行工作。VB.net httpwebrequest For循環掛起每10個左右的迭代
這裏是我到目前爲止有:
For i As Integer = 0 To numberOfProxies - 1
Try
'create request to a proxyJudge php page using proxy
Dim request As HttpWebRequest = HttpWebRequest.Create("http://www.pr0.net/deny/azenv.php")
request.Proxy = New Net.WebProxy(proxies(i)) 'select the current proxie from the proxies array
request.Timeout = 10000 'set timeout
Dim response As HttpWebResponse = request.GetResponse()
Dim sr As StreamReader = New StreamReader(response.GetResponseStream())
Dim pageSourceCode As String = sr.ReadToEnd()
'check the downloaded source for certain phrases, each identifies a type of proxy
'HTTP_X_FORWARDED_FOR identifies a transparent proxy
If pageSourceCode.Contains("HTTP_X_FORWARDED_FOR") Then
'delegate method for cross thread safe
UpdateListbox(ListBox3, proxies(i))
ElseIf pageSourceCode.Contains("HTTP_VIA") Then
UpdateListbox(ListBox2, proxies(i))
Else
UpdateListbox(ListBox1, proxies(i))
End If
Catch ex As Exception
'MessageBox.Show(ex.ToString) used in testing
UpdateListbox(ListBox4, proxies(i))
End Try
completedProxyCheck += 1
lblTotalProxiesChecked.CustomInvoke(Sub(l) l.Text = completedProxyCheck)
Next
我已經找遍了這個網站,並通過谷歌,以及這類問題的大多數答覆說,響應必須關閉。我已經嘗試了使用塊,如:
Using response As HttpWebResponse = request.GetResponse()
Using sr As StreamReader = New StreamReader(response.GetResponseStream())
Dim pageSourceCode As String = sr.ReadToEnd()
'check the downloaded source for certain phrases, each identifies a type of proxy
'HTTP_X_FORWARDED_FOR identifies a transparent proxy
If pageSourceCode.Contains("HTTP_X_FORWARDED_FOR") Then
'delegate method for cross thread safe
UpdateListbox(ListBox3, proxies(i))
ElseIf pageSourceCode.Contains("HTTP_VIA") Then
UpdateListbox(ListBox2, proxies(i))
Else
UpdateListbox(ListBox1, proxies(i))
End If
End Using
End Using
而且它沒有什麼區別(雖然我可能已經實現了這是錯誤的)你可以告訴IM到VB很新或任何OOP所以它可能是一個簡單的問題,但我不能解決它。
任何意見或只是提示如何診斷這些類型的問題將非常感激。編輯: 現在即時通訊徹底困惑。 try catch語句是否自動關閉響應,還是我需要在finally中放置一些東西?如果是這樣,什麼?我不能使用response.close(),因爲它在try塊中聲明。
也許我只是使用非常糟糕的結構化代碼,並有更好的方法來做到這一點?或其他什麼導致暫停/掛起?
關於第二塊代碼,這裏並沒有涉及到:「使用塊的行爲就像Try ...最後的構造,其中Try塊使用資源,Finally塊處理它們。因此,無論您如何退出塊,Using塊都保證資源的處理,即使在未處理的異常情況下也是如此,除了StackOverflowException。「請參閱MSDN http://msdn.microsoft.com/en-us/library/htd05whh%28v=VS.100%29.aspx – apros
好吧,所以最後看看那個和try catch的相關頁面,看起來我的原創代碼是關閉響應的權利?或者我需要添加一些東西最後 - 我試着在那裏添加response.close(),但它不起作用,因爲在try塊中聲明瞭響應。 – Steve
但是,您可以輕鬆地在try塊之外聲明responese對象,然後在try-catch-finally中實例化它。這將幫助你在finally塊中使用response.close()塊 – apros