此代码开始使用 40 MB RAM,2 小时后使用 120 MB RAM。我试图改变一些行,但使用的内存仍然上升和上升。我究竟做错了什么?是while循环吗?是大头吗?是 ContextDB.SaveChanges() 吗?
更新 1:显然问题已解决,在线程上使用“IsBackground = True”并处理每个“m”对象。使用的 RAM 稳定在 48 MB。多谢你们。
Dim Work As New Thread(AddressOf MonitorServer)
Work.IsBackground = True 'Added this line
Work.Start(Server.ServerID)
Using searcher As New ManagementObjectSearcher(Scope, New ObjectQuery("SELECT * FROM Win32_OperatingSystem"))
Using queryCollection = searcher.Get()
For Each m In queryCollection
Server.Host = m("csname")
Server.OS = m("Caption")
m.Dispose() 'Added this line
m = Nothing 'Added this line
Next
End Using
End Using
.
更新 2:问题继续存在,24 小时后,代码使用了350 MB!!!
.
原始代码:
Full code: http://200.98.144.175/monitor.txt
Private Shared ServerList As New List(Of Server)
Private Shared Sub StartMonitor()
Using ContextDB As New EnvironmentMonitorEntities
While True
Dim Servers = (From A In ContextDB.Server).ToList
For Each Server In Servers
If Not ServerList.ToList.Contains(Server) Then
ServerList.Add(Server)
Dim Work As New Thread(AddressOf MonitorServer)
Work.Start(Server) 'Start a thread for each server
End If
Next
GC.Collect() 'Force CG
Thread.Sleep(CInt(TimeSpan.FromSeconds(10).TotalMilliseconds)) 'Check new servers each 10 seconds
End While
End Using
End Sub
Private Shared Sub MonitorServer(p As Object)
Dim Server = CType(p, Server)
Using ContextDB As New EnvironmentMonitorEntities
While True
Dim ServerID = Server.ServerID
Dim ServerStatus = (From A In ContextDB.ServerStatus Where A.ServerID = ServerID).First
Dim Scope As New ManagementScope("\\" + Server.IP + "\root\CIMV2")
ServerStatus.LastUpdate = Now
ContextDB.SaveChanges()
Scope.Connect() 'Connect on server
Alerts.SetServerStatus(ServerStatus, AlertType.Online)
ContextDB.SaveChanges()
Using searcher As New ManagementObjectSearcher(Scope, New ObjectQuery("SELECT * FROM Win32_OperatingSystem"))
Using queryCollection = searcher.Get()
For Each m In queryCollection
Server.Host = m("csname")
Server.OS = m("Caption")
Next
End Using
End Using
ContextDB.SaveChanges()
Using searcher As New ManagementObjectSearcher(Scope, New ObjectQuery("SELECT * FROM Win32_Processor"))
Using queryCollection = searcher.Get()
For Each m In queryCollection
Server.Processor = m("Name")
Server.Architecture = m("Architecture")
Next
End Using
End Using
ContextDB.SaveChanges()
Using searcher As New ManagementObjectSearcher(Scope, New ObjectQuery("SELECT * FROM Win32_OperatingSystem"))
Using queryCollection = searcher.Get()
For Each m In queryCollection
ServerStatus.RAMUsage = m("FreePhysicalMemory")
ContextDB.SaveChanges()
Next
End Using
End Using
GC.Collect()
Thread.Sleep(CInt(TimeSpan.FromSeconds(3).TotalMilliseconds)) 'Monitor server each 3 seconds
End While
End Using 'ContextDB
End Sub