Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,
I have 2 threads connecting communicating with the server through different ports, if the server is not ready, it's gonna pause for a while (thread.sleep) and retry.
The connection attempts is in a while loop, when the first thread starts, the CPU is about 50% utilized, when the second thread starts the CPU is fully utilized and everything on the machine starts to crash, hang, ..., etc
This is a Windows Service, it has primary connection with the main server, the primary connection has a listener thread that receives transactions, the secondary connection is for requesting transactions reload form the server, when the reload thread starts, the main connection is still active, both connections have different port number, actually I have 2 main connections and 2 secondary connections (different ports), because I receive different type of transactions on each port.

This subroutine starts the reload thread.
VB
Private Sub startRealodThread()
       If Not isReloadThreadWorking Then
           IsProcessingReloadQueue = True
           Try
               ResponseMonitorService.wcfService.setReloading(True, myType)
               Me.selfReloading = True
               Dim ReloadThread As New Thread(AddressOf requestReload)
               ReloadThread.Name = "ReloadThread" & "_" & strMyType
               ReloadThread.SetApartmentState(Threading.ApartmentState.STA)
               ReloadThread.Start()
               RESET_STATUS = CommandStatus.NoCommand
           Catch ex As Exception
              ' Write log
           End Try
       End If
   End Sub


The reload thread:
VB
 Private Sub requestReload()
    isReloadThreadWorking = True
    Dim ResetCommand As String = STX & "\/RESET" & ETX
    Dim RetryCount As Integer = 0
    Dim strData As String = ""
    Dim waiting As Boolean = True, sendACK As Boolean
    Dim reloader As New TcpClient
    Dim ConnCount As Integer = 1
    Dim reloadStream As NetworkStream
    Dim done As Boolean = False
    Dim wrongAckCount As Integer = 0
    On Error Resume Next

    While Not reloader.Connected
        If ExitReloadThread Then
            Me.selfReloading = False
            Me.needsReload = True
            reloadStream.Close()
            reloader.Close()
            ExitReloadThread = False
            isReloadThreadWorking = False
            Exit Sub
        End If

        Select Case RESET_STATUS
            Case CommandStatus.AboutToSend
                ' Write log
            Case CommandStatus.AckReceived
                ' Write Log
            Case CommandStatus.AckVerified
                ConnCount += 1

                Dim ar As System.IAsyncResult = reloader.BeginConnect(Me.ip, Val(Me.port) + 20000, Nothing, Nothing)
                Dim wh As WaitHandle = ar.AsyncWaitHandle
                If Not ar.AsyncWaitHandle.WaitOne(1500, False) Then
                    ' The logic to control when the connection timed out
                     reloader.Close()
                     'Throw New TimeoutException()
                Else
                    ' The logic to control when the connection succeeds.
                    reloader.EndConnect(ar)
                End If
                wh.Close()

                If Not reloader.Connected Then
                    reloader.Close()
                End If
            Case CommandStatus.ExpectingAck
                    'Write log
            Case CommandStatus.NoCommand
                RESET_STATUS = CommandStatus.Preparing
                ResponseMonitorService.wcfService.setReloading(True, myType)
                Me.selfReloading = True
                ResetTimeOutTimer.Start()
                Me.sendData(ResetCommand, Me.oLogEntity_Reload, True)
            Case CommandStatus.Preparing
                ' Write Log
            Case CommandStatus.Retry
                RetryCount += 1
                If RetryCount = 3 Then
                    ExitReloadThread = True
                End If
                RESET_STATUS = CommandStatus.NoCommand
            Case CommandStatus.SendFailed
                RESET_STATUS = CommandStatus.Retry
            Case CommandStatus.TimeOut
                ResetTimeOutTimer.Stop()
                RESET_STATUS = CommandStatus.Retry
            Case CommandStatus.WrongAck
                If wrongAckCount = 3 Then
                    ExitReloadThread = True
                Else
                    wrongAckCount += 1
                    RESET_STATUS = CommandStatus.ExpectingAck
                End If
        End Select
        ' Pause for 500 millisecond to fix the CPU utilization problem (Didn't work)
            Thread.Sleep(500)
    End While

    ' here we read and process the transactions ...
    '
    '
    '
    '

End Sub


Please help me to find the problem, I know it's in the while loop, it's excessively utilizing the CPU, I used thread.sleep but it didn't work!

Thanks


**** Update ****

I found that the first thread gets connected without problems, when the second thread attempts to connect, then the CPU is 100% used.
It is stuck exactly on
VB
If Not ar.AsyncWaitHandle.WaitOne(1500, False) Then


Any help is appreciated!
Posted
Updated 17-Oct-12 7:03am
v2
Comments
pasztorpisti 16-Oct-12 18:51pm    
The first codeblock with its infinite loop looks weird, how many threads do your create with it?
Sameer Alomari 16-Oct-12 18:59pm    
It's not considered as infinite loop, this loop will exit once the port is closed (the server completed the reload transactions), the last transaction will notify the thread that the server is done and it's gonna exit the loop.
I have 2 threads running the same code.

1) Using your debugger, step through the code which is pinning your CPU. Find out what calls are actually the problem. Just adding a random sleep command in is like putting a band-aid on a 2 inch gash. You may appear to have solved the problem, but it won't heal the root issue.
2) Once you find the problem line(s) of code, investigate them and make them not pin the CPU. Post some code surrounding where the root problem exists and we can see if we can help you solve your issue.
 
Share this answer
 
**** Update ****

I found that the first thread gets connected without problems, when the second thread attempts to connect, then the CPU is 100% used.
It is stuck exactly on
VB
If Not ar.AsyncWaitHandle.WaitOne(1500, False) Then


Any help is appreciated!
 
Share this answer
 
I found that there was a tight loop!!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900