Results 1 to 5 of 5

Thread: Problem with increased CPU usage in multi-threaded application

  1. #1

    Thread Starter
    New Member
    Join Date
    May 2009
    Posts
    3

    Problem with increased CPU usage in multi-threaded application

    I have a VS2022 application that is multi-threaded. A TCP Listener listens to a network port for incoming connections. If pending, a thread is spawned to process the connection. The thread process is in another class. When processing is complete, the thread exits. The problem is, as the days go by, the CPU usage keeps increasing. This indicates to me that something is still running. However,

    1. The application shows that the thread has been exited at the end of every process.
    2. I have a variable within the class that checks to see if a thread is still running after 3 hours. If it is the thread exits. I have not seen this happen.

    If I run the application within VS2022, I do not see this behavior. I have been trying to figure this out for over a year with no progress. Has anyone seen this behavior?

    Thanks in advance.

  2. #2
    PowerPoster yereverluvinuncleber's Avatar
    Join Date
    Feb 2014
    Location
    Norfolk UK (inbred)
    Posts
    2,410

    Re: Problem with increased CPU usage in multi-threaded application

    I should imagine the chaps here will want to see some code to see how and what you are actually doing. Show us the steps you are doing to see it actually happening, otherwise it is a bit vague.
    https://github.com/yereverluvinunclebert

    Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.

    By the power invested in me, all the threads I start are battle free zones - no arguing about the benefits of VB6 over .NET here please. Happiness must reign.

  3. #3

    Thread Starter
    New Member
    Join Date
    May 2009
    Posts
    3

    Re: Problem with increased CPU usage in multi-threaded application

    The application is quite extensive. Following is the TCP Listener in the main UI.

    Code:
        'Fires every second to get TCP connections.
        Private Sub tcpTimer_Tick(sender As Object, e As System.EventArgs) Handles tcPTimer.Tick
            Try
    
                'If a TCP connection is pending and the number of connections is not maxed out.
                If tcpListen.Pending Then
    
                    'Clear the log text if more than 50000 characters.
                    If tbLog.TextLength > 50000 Then tbLog.Clear()
    
                    'Initialize a new processing reference.
                    Dim proc As New Processing()
    
                    'Start a new thread.
                    Dim tcpThread As New System.Threading.Thread(AddressOf proc.incoming)
                    tcpThread.SetApartmentState(System.Threading.ApartmentState.STA)
                    tcpThread.IsBackground = True
                    tcpThread.Start()
                End If
    
                'If a threading error.
            Catch ex As Exception
                tcpListen.Stop()
                tcpListen.Start()
                tbLog.AppendText(Format(Now, "yyyy-MM-dd HH:mm:ss") & " - Error in TCP thread. " & ex.Message & vbCrLf & vbCrLf)
            End Try
        End Sub
    Then the code for the incoming routine in the Processing class.

    Code:
       'If data is received on the TCP port.
       Public Sub incoming()
    
           noNewEvents = False
           threadAbort = False
           threadTimer = New Timer
           threadTimer.Interval = 10800000
           threadTimer.Start()
    
           'Intialize a network stream.
           Dim stream As NetworkStream = FormRef.tcpListen.AcceptTcpClient.GetStream
    
           'Initialize byte list to hold data bytes.
           Dim recordBytes As New List(Of Byte)
    
           'Initialize a 1024 character read buffer.
           Dim myReadBuffer(1023) As Byte
    
           'Holds number of bytes read.
           Dim numberOfBytesRead As Integer = 0
    
           'Holds bytes converted to text.
           Dim textData As String = ""
    
           'Initialize a variable to track elapsed time.
           Dim start As Single = DateAndTime.Timer
           Dim found As Boolean = False
    
           'Loop to read data.
           Do
    
               If threadAbort Then Exit Do
    
               'If data is available in the stream.
               If stream.DataAvailable Then
    
                   'Update the time variable.
                   start = DateAndTime.Timer
    
                   'Get number of bytes to read.
                   numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length)
    
                   'Initialize an array to hold the bytes.
                   Dim newBytes(numberOfBytesRead - 1) As Byte
    
                   'Copy the contents of the data buffer to the array.
                   Array.Copy(myReadBuffer, newBytes, numberOfBytesRead)
    
                   'Add the bytes read to the data list.
                   recordBytes.AddRange(newBytes)
    
                   'Convert byte list to text.
                   textData = System.Text.Encoding.GetEncoding(28591).GetString(recordBytes.ToArray)
    
                   'If text data contains a YY (event report) or YH (heartbeat)
                   If recordBytes.Count >= 4 And (textData.Contains("YY") Or textData.Contains("YH")) Then
    
                       'Set the flag. Exit the loop.
                       found = True
                       Exit Do
                   End If
               End If
    
               'Loop until the elapsed time exceeds the user defined latency.
           Loop Until DateAndTime.Timer - start > My.Settings.TCPLatency
    
           'If a valid report string and abort flag is false.
           If found And Not threadAbort Then
    
               'Initialize unit SN and get the reporting SN.
               dataSN = 0
               getSN(recordBytes, stream)
           End If
    
           'If SN is not 0 and there are new events, report thread closed.
           If dataSN > 0 And Not noNewEvents Then
               FormRef.SetText(dataSN & " - " & Format(Now, "yyyy-MM-dd HH:mm:ss") & " - Thread closed." & vbCrLf & vbCrLf)
           End If
       End Sub
    Maybe this will help.

  4. #4
    PowerPoster yereverluvinuncleber's Avatar
    Join Date
    Feb 2014
    Location
    Norfolk UK (inbred)
    Posts
    2,410

    Re: Problem with increased CPU usage in multi-threaded application

    Hold on for more responses, chaps from the rest of the world will start to chime in later.
    https://github.com/yereverluvinunclebert

    Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.

    By the power invested in me, all the threads I start are battle free zones - no arguing about the benefits of VB6 over .NET here please. Happiness must reign.

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,665

    Re: Problem with increased CPU usage in multi-threaded application

    Quote Originally Posted by SeismoDude View Post
    2. I have a variable within the class that checks to see if a thread is still running after 3 hours. If it is the thread exits. I have not seen this happen.
    Seems you already know the problem. Figure out why these threads aren't being terminated when they should be. Threads are quite resource heavy and will eat your CPU cycles and memory.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width