我想通过一个循环,但只有在抛出异常时才返回循环。我怎么写这个在vb.net?我正在尝试使用代理服务器发出Web请求。这是我到目前为止的代码,目前无效。
Public Sub checkproxy()
Dim myWebRequest As WebRequest = WebRequest.Create("http://www.contoso.com")
Dim myProxy As New WebProxy()
Dim proxyAddress = "http://www.example.com:8080"
Dim newUri As New Uri(proxyAddress)
myProxy.Address = newUri
myWebRequest.Proxy = myProxy
Dim switch As String = "b"
Dim myWebResponse As WebResponse
Do Until switch = "a"
Try
myWebRequest.GetResponse()
switch = "a"
Catch ex As Exception
System.Threading.Thread.Sleep(5000)
End Try
Loop
RichTextBox1.Text = myWebResponse.Headers.ToString
myWebResponse.Close()
ToolStripStatusLabel1.Text = "Connected"
End Sub
答案 0 :(得分:2)
Exit Do
正在寻找:
Do Until switch = "a"
Try
myWebRequest.GetResponse()
switch = "a"
Exit Do
Catch ex As Exception
System.Threading.Thread.Sleep(5000)
End Try
Loop
答案 1 :(得分:1)
实际上,您需要做的就是将Do Until ... Loop
更改为Do ... Loop Until
,它将始终运行循环一次,然后在再次执行循环之前检查循环条件:
Do
Try
myWebRequest.GetResponse()
switch = "a"
Catch ex As Exception
System.Threading.Thread.Sleep(5000)
End Try
Loop Until switch = "a"
有关语法和进一步说明,请参阅Do Loop page
答案 2 :(得分:0)
我需要{MarisJuraszek所述的Exit Do
回答我还需要在try函数中创建webrequest而不是在代码的开头。这是工作代码的更新。
Public Sub checkproxy()
Dim myWebRequest As WebRequest
Dim myProxy As New WebProxy()
Dim proxyAddress = "http://www.example.com:8080"
Dim newUri As New Uri(proxyAddress)
myProxy.Address = newUri
Dim switch As String = "b"
Dim myWebResponse As WebResponse
Do Until switch = "a"
Try
myWebRequest = WebRequest.Create("http://www.contoso.com")
myWebRequest.Proxy = myProxy
myWebResponse = myWebRequest.GetResponse()
switch = "a"
Exit Do
Catch ex As Exception
System.Threading.Thread.Sleep(5000)
End Try
Loop
RichTextBox1.Text = myWebResponse.Headers.ToString
myWebResponse.Close()
ToolStripStatusLabel1.Text = "Connected"
End Sub
答案 3 :(得分:0)
不需要此开关。
Do While True
Try
myWebRequest.GetResponse()
Exit Do
Catch ex As Exception
System.Threading.Thread.Sleep(5000)
End Try
Loop
此外,明智的做法是允许用户在设置的时间后退出循环,以避免无限循环。