Solved

VB.NET OutOfMemoryException Error

Posted on 2014-10-23
9
280 Views
Last Modified: 2014-11-09
I use Socket to communicate with the hardware called MW100 and read the data from it by calling Sub  SendRequestToMW100 every five seconds.

The Initial connection is good, now after about 25 Minutes running time, I got the System.OutOfMemoryException error from the line: Dim inStream(10024) As Byte


Could anybody help me with this?

My Code likes this:

 Dim clientSocket As New System.Net.Sockets.TcpClient()
 Dim serverStream As NetworkStream

    Public Sub SendRequestToMW100()

        Dim term As String = Chr(10)

        Dim serverStream As NetworkStream = clientSocket.GetStream()
        Dim outStream As Byte() = _
        System.Text.Encoding.ASCII.GetBytes("FD0, 001, 060" & term)

           Try              
                serverStream.Write(outStream, 0, outStream.Length)

            Catch ex As Exception
                MsgBox(ex.Message)

            End Try
            serverStream.Flush()

            Dim inStream(10024) As Byte
            Try
                serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))

            Catch ex As Exception
                MsgBox(ex.Message)

            End Try
            Dim returndata As String = _
            System.Text.Encoding.ASCII.GetString(inStream)
            msg("Data from Server : " + returndata)
       
    End Sub
0
Comment
Question by:charlieb01
  • 3
  • 2
  • 2
  • +1
9 Comments
 
LVL 40
ID: 40400879
You do not call Close or Dispose on you NetworkStream when you are finished with it, so its data stays in memory.

Whenever you see that a class that has a Dispose method (at least in the Framework methods), it is recommended to call it (or Open, which does the same thing form streams) before you lose your variable. That forces the object to cleanup behind itself.

A simple serverStream.Close before the End Sub would probably solve your problem.
0
 

Author Comment

by:charlieb01
ID: 40400983
I tried putting serverStream.Close at the place indicated but then I did not get any returned data at all, unless I got one reading and missed it. Is there a  better place to put the Close. All of my code from the module is here:
Imports System.Net.Sockets
Imports System.Text


Module modMW100Communication

    Dim clientSocket As New System.Net.Sockets.TcpClient()
    Dim serverStream As NetworkStream

    Public RemoteHostAddress As String = My.Settings.MW100IPAddr

    Const portNumber As Integer = 34318

    Public MW100SourceIsMW100%

    Public Sub ConnectToMW100()

        If MW100SourceIsMW100 Then
            Try
                clientSocket.Connect(RemoteHostAddress, portNumber)

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Public Sub SendRequestToMW100()

        Dim term As String = Chr(10)

        Dim serverStream As NetworkStream = clientSocket.GetStream()
        Dim outStream As Byte() = _
        System.Text.Encoding.ASCII.GetBytes("FD0, 001, 060" & term)

        If MW100SourceIsMW100 Then
            Try
                serverStream.Write(outStream, 0, outStream.Length)

            Catch ex As Exception
                MsgBox(ex.Message)

            End Try
            serverStream.Flush()

            Dim inStream(10024) As Byte
            Try
                serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))

            Catch ex As Exception
                MsgBox(ex.Message)

            End Try
            Dim returndata As String = _
            System.Text.Encoding.ASCII.GetString(inStream)
            msg("Data from Server : " + returndata)
        End If
        serverStream.Close()          'TRIED THIS BUT THEN DID NOT GET ANY DATA RETURNED AT ALL OR PERHAPS I GOT ONE READING
    End Sub
    Public Sub CloseMW100Socket()
        If MW100SourceIsMW100 Then
            clientSocket.Close()
        End If
    End Sub
    Public Sub msg(ByVal mesg As String)
        Dim aryMessage() As String
        Dim longterm As String = Chr(13) & Chr(10)
        Dim intIndex As Integer

        If InStr(mesg, ": EA") > 0 Then
            If InStr(mesg, "N 001") > 0 Then
                aryMessage = Split(Trim(mesg), longterm)
                For intIndex = 0 To 64
                    If InStr(aryMessage(intIndex), "EN") > 0 Then
                        Exit Sub
                    Else
                        If InStr(aryMessage(intIndex), "+") > 0 Then
                            'Debug.Print(Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "+"), 10).ToString)
                            'Form1.TextBox1.Text = Form1.TextBox1.Text + Environment.NewLine + Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "+"), 10).ToString

                            AinElec(intIndex - 3) = Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "+"), 10).ToString
                        ElseIf InStr(aryMessage(intIndex), "-") > 0 Then
                            'Debug.Print(Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "-"), 10).ToString)
                            'Form1.TextBox1.Text = Form1.TextBox1.Text + Environment.NewLine + Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "-"), 10).ToString
                            AinElec(intIndex - 3) = Mid(aryMessage(intIndex), InStr(aryMessage(intIndex), "-"), 10).ToString
                        End If

                    End If
                Next
            End If

        End If
    End Sub
End Module

Open in new window

0
 
LVL 40
ID: 40401157
The information I gave you was with my experience with hundred of classes in the Framework.

Looking at the documentation, I see that there is an alternate Close method that you can use with the NetworkStream. You can specify a number of milliseconds to wait before really closing, which leaves time for the Stream to finish its job. The time required has to be found through trial and error. You can start with 1 second:

serverStream.Close(1000)
0
 

Author Comment

by:charlieb01
ID: 40410468
Sorry for the delay in response - got sidetracked. Adding the delay didn't help at all
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
ID: 40411808
Try adding

inStream = Nothing
GC.Collect


as the last two lines in your sub.
0
 
LVL 27

Expert Comment

by:Ark
ID: 40417970
Why are you declaring serverStream twice - at module level and at sub level?
0
 
LVL 27

Expert Comment

by:Ark
ID: 40418011
PS. Try use dynamic array instead of static:
Dim inStream() As Byte
Dim buffSize=clientSocket.ReceiveBufferSize
If buffSize > 0 Then
    Redim inStream(buffSize-1)
            Try
                serverStream.Read(inStream, 0, buffSize)
'rest of code
End If

Open in new window

0
 

Author Closing Comment

by:charlieb01
ID: 40431131
It took us a while but we discovered all kinds of places where we could clean up code, disposing of forms, data tables, etc. and then using the GC.Collect

Thanks for your help. This was a tedious process as the only way to test it is to just let it run for hours.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 40431314
Glad its fixed :-)
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now