我使用.net 4.0在vb中编写了一个URL监控程序。基本上它设置一个计时器使用htpwebreques / httpwebresponse每隔60分钟检查一次网址,并在网址关闭时发送一封电子邮件。但是,每次检查URL时,应用程序使用的内存都会不断增加。这显然会导致问题,因为应用程序旨在永久监控网站的可用性,监控机器最终会耗尽资源。
下面的CheckURL例程代码。任何建议都非常感谢,提前感谢。
Private Sub checkURL()
Timer1.Stop()
Dim wReq As HttpWebRequest
Dim wResp As HttpWebResponse ' WebResponse
wReq = HttpWebRequest.Create(url)
wReq.Method = "HEAD"
Try
wResp = wReq.GetResponse()
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
wResp = Nothing
wReq = Nothing
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub
答案 0 :(得分:0)
首先,您应该使用Option Strict On,它会向您显示变量类型不匹配的位置,甚至可能会为您建议更正,例如,请参阅以下代码中DirectCast
运算符的使用位置
其次,HttpWebResponse
有.Dispose()
方法,因此您应该在使用完毕后调用它,或者,正如Zaggler指出的那样,您可以使用Using
来确保不受管理资源被正确清理,从而消除了您所关心的内存泄漏。请注意,我们无法看到的代码中可能存在其他类似问题。
你应该不将东西设置为Nothing
以试图摆脱它们 - 这样做会对垃圾收集器造成混乱,并且无法确保它们的清洁处理。
Option Strict On
' ....
Private Sub checkURL()
timer1.Stop()
Dim wReq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
wReq.Method = "HEAD"
Try
Using wResp As HttpWebResponse = DirectCast(wReq.GetResponse(), HttpWebResponse)
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
End Using
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub