473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Multi-threaded app memory leak

J
Hi,

I've written a multi threaded application which scans about 2000
servers event logs to check for disk errors.

The problem with it is due to the fact that it just keeps eating
memory. In the end it's used up the best part of 100Mb, which I think
is excessive.

For each server it checks, it creates a new EventHelper object and
then executes a method which collects the data via a new thread. The
CheckEventLogs method rasies an event when it's completed and that
calls another method in the original code which writes the data to a
temp file.

Can anyone point me in the direction of what I'm doing wrong here and
the correct method for doing this?

Module1.vb ################################################## ###

Imports System.Threading

Module Module1

Dim RunningThreads As Integer = 0
Dim MaxThreads As Integer = 30

Sub Main()

RunProcess()

End Sub

Private Sub RunProcess()

If ServerList.Count = 0 Then End

Thread.CurrentThread.Name = "Main Thread"

Dim EventChecks(ServerList.Count - 1) As EventHelper
Dim t As Thread

For i As Integer = 0 To ServerList.Count - 1

EventChecks(i) = New EventHelper
EventChecks(i).ID = i
EventChecks(i).ServerName = ServerList(i)
AddHandler EventChecks(i).TaskCompleted, AddressOf
ProcessResults
t = New Thread(New ThreadStart(AddressOf
EventChecks(i).CheckEventLogs))
t.Name = String.Format("{0}", EventChecks(i).ID)
t.IsBackground = True
t.Start()
RunningThreads += 1

Do While RunningThreads >= MaxThreads + 1
Thread.Sleep(10000)
Loop

Next

Do Until RunningThreads = 0
Thread.Sleep(200)
Loop

End Sub

Private Function GetServerList() As ArrayList

Dim myList As New ArrayList

' Attains server list from source ....

Return myList

End Function
Private Sub ProcessResults(ByVal sender As Object)

RunningThreads -= 1

Dim Results As EventHelper = DirectCast(sender, EventHelper)

Dim id As String = Results.ID

Console.WriteLine("ThreadID {0} complete (Server: {1}).
Running processes: {2}. {3}", id, Results.ServerName, RunningThreads,
Results.ErrorMessage)

TempFileWriter.WriteTempFile(DirectCast(sender, EventHelper))

Results.Dispose()
Results = Nothing
sender = Nothing

End Sub

End Module

################################################## #############

EventHelper.vb

Imports System.Management

Public Class EventHelper

Implements IDisposable

Event TaskCompleted(ByVal sender As Object)

Public ID As Integer = 0
Public ServerName As String = String.Empty
Public DaysToCheck As Double = 1.0
Public PhysicalDiskFail As Boolean = False
Public PredictiveDiskFail As Boolean = False
Public LogicalFail As Boolean = False
Public SANPathIssue As Boolean = False
Public BadBlock As Boolean = False
Public CorruptFilesystem As Boolean = False
Public BattteryFailure As Boolean = False
Public ErrorMessage As String = String.Empty

Public Sub New()

End Sub

Public Sub CheckEventLogs()

If Not ServerOnline(Me.ServerName) Then
ErrorMessage = String.Format("{0} - Server offline",
Me.ServerName)
RaiseEvent TaskCompleted(Me)
Exit Sub
End If

Me.ServerName = Me.ServerName.ToUpper.Trim

Dim EndDate As DateTime = Now
Dim StartDate As DateTime = DateAdd(DateInterval.Day, -
DaysToCheck, EndDate)

' Convert to WMI dates
Dim strEndDate As String = Year(EndDate) & Right("00" &
Month(EndDate), 2) & Right("00" & Day(EndDate), 2) & Right("00" &
Hour(Now), 2) & Right("00" & Minute(Now), 2) & "00.000000+060"
Dim strStartDate As String = Year(StartDate) & Right("00" &
Month(StartDate), 2) & Right("00" & Day(StartDate), 2) &
"000000.000000+060"

Dim SelectStatement As String = String.Format("Select * from
Win32_NTLogEvent Where TimeWritten >= '{0}' and TimeWritten < '{1}'
AND LogFile = 'system' and (SourceName = 'storage agents' OR
SourceName = 'CPQCISSE' OR SourceName = 'ntfs' OR SourceName =
'EmcpBase' OR SourceName = 'Disk') AND (EventType =1 OR EventType =
2)", strStartDate, strEndDate)

Dim Scope As ManagementScope
Dim Options As ConnectionOptions
Dim Query As ObjectQuery
Dim WMIInfo As ManagementObjectSearcher

Try

Scope = New ManagementScope
Options = New ConnectionOptions
Query = New ObjectQuery(SelectStatement)
WMIInfo = New ManagementObjectSearcher

With Options

.Impersonation = ImpersonationLevel.Impersonate
.Authentication = AuthenticationLevel.Packet

End With

Scope = New ManagementScope("\\" & Me.ServerName & "\root
\cimv2", Options)
Scope.Connect()

If Scope.IsConnected = False Then
Exit Sub
End If

WMIInfo.Scope = Scope
WMIInfo.Query = Query

For Each Info As ManagementObject In WMIInfo.Get

CheckForErrors(Info)

Next

Catch ex As Exception

ErrorMessage = String.Format("EventHelper: {0}",
ex.Message)

ErrorLogHelper.WriteError(String.Format("EventHelp er:
{0}", ex.Message), Me.ServerName)

Finally

If Not IsNothing(WMIInfo) Then WMIInfo.Dispose()

RaiseEvent TaskCompleted(Me)

End Try

End Sub

Private Sub CheckForErrors(ByVal EventInfo As ManagementObject)

Dim EventCode As Int16 =
Convert.ToInt16(EventInfo("EventCode"))
Dim EventMsg As String = CStr(EventInfo("Message"))

Select Case EventCode

' Code removed for brevity

End Select

End Sub

Private Function ServerOnline(ByVal Server As String) As Boolean

Dim objStatus As ManagementObject
Dim objPing As New SelectQuery("Select StatusCode from
Win32_PingStatus WHERE Address = '" & Server & "' and statuscode = 0")
Dim Search As New ManagementObjectSearcher(objPing)

ServerOnline = (Search.Get.Count = 1)

objPing = Nothing
objStatus = Nothing
Search = Nothing

End Function

Public Overloads Sub Dispose() Implements IDisposable.Dispose

Dispose(True)
GC.SuppressFinalize(Me)

End Sub ' Dispose

Protected Overridable Overloads Sub Dispose(ByVal disposing As
Boolean)

If disposing Then

ID = Nothing
ServerName = Nothing
DaysToCheck = Nothing
PhysicalDiskFail = Nothing
PredictiveDiskFail = Nothing
LogicalFail = Nothing
SANPathIssue = Nothing
BadBlock = Nothing
CorruptFilesystem = Nothing
BattteryFailure = Nothing
ErrorMessage = Nothing

End If

End Sub ' Dispose

End Class
Jan 14 '08 #1
1 1702
J <jo****@gmail.comwrote in news:f3573502-8db8-4be0-bd8a-ef7a66cd26a1
@q39g2000hsf.googlegroups.com:
Can anyone point me in the direction of what I'm doing wrong here and
the correct method for doing this?
Threads use memory - perhaps look at using the Threadpool instead.

Also .NET will use memory until the GC kicks in, so don't worry too much
about memory usage unless it keeps going up and up and doesn't stablize.

--
sp**********@rogers.com (Do not e-mail)
Jan 14 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours,...
4
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio 2003 Regards Frank
12
by: * ProteanThread * | last post by:
but depends upon the clique: ...
0
by: frankenberry | last post by:
I have multi-page tiff files. I need to extract individual frames from the multi-page tiffs and save them as single-page tiffs. 95% of the time I receive multi-page tiffs containing 1 or more black...
6
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
6
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME The other multi-list box displays courses based on...
4
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the...
5
by: Shane Story | last post by:
I can seem to get the dimensions of a frame in a multiframe tiff. After selecting activeframe, the Width/Height is still really much larger than the page's actual dimensions. When I split a...
0
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing...
1
by: mknoll217 | last post by:
I am recieving this error from my code: The multi-part identifier "PAR.UniqueID" could not be bound. The multi-part identifier "Salary.UniqueID" could not be bound. The multi-part identifier...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.