Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C threads VB.NET TCP/IP service , +
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.
 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:
 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
If Not ar.AsyncWaitHandle.WaitOne(1500, False) Then

Any help is appreciated!
Posted 16-Oct-12 5:27am
Edited 17-Oct-12 7:03am
v2
Comments
pasztorpisti at 16-Oct-12 18:51pm
   
The first codeblock with its infinite loop looks weird, how many threads do your create with it?
Sameer Alomari at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

I found that there was a tight loop!!
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

**** 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
If Not ar.AsyncWaitHandle.WaitOne(1500, False) Then
 
Any help is appreciated!
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 554
1 Gihan Liyanage 298
2 ChintanShukla 295
3 RyanDev 250
4 Richard Deeming 250
0 Sergey Alexandrovich Kryukov 8,906
1 OriginalGriff 7,601
2 CPallini 2,603
3 Richard MacCutchan 2,121
4 Abhinav S 1,923


Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 20 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100