Program memory cleaning in use

Asked

Viewed 1,361 times

3

My application is accumulating memory, only thing it does, that’s the bottom.

After 10-15 minutes, it comes to consume more than 1.5GB of memory, and continues consumption non-stop.

Run a Timer every two minutes its function is:

Private Sub postGrupo_Tick(sender As Object, e As EventArgs) Handles postGrupo.Tick
    ProgressBarStatus.Value = ProgressBarStatus.Value + 1
    Try
        StartPostGrupos()
    Catch ex As Exception

    End Try
End Sub

Sub StartPostGrupos()
Dim value As Integer = ProgressBarStatus.Value
    Select Case value
        Case 10
            If WebBrowser1.DocumentText.Contains("Iniciar discussão") = True Then
                For Each element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
                    If element.GetAttribute("data-endpoint") = "/ajax/composerx/attachment/group/post/" Then
                        element.InvokeMember("click")
                    End If
                Next
            End If
        Case 20
            If postImgGo = 1 Then
                If File.Exists(imgGroupsDir & imgGroupsName) Then
                    For Each element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
                        If element.GetAttribute("data-endpoint") = "/ajax/composerx/attachment/media/chooser/" Then
                            element.InvokeMember("click")
                        End If
                    Next
                    selecionarIMG.Start()
                End If
            End If
        Case 50
            Dim FILE_NAME As String = "config/msgGroups.txt"
            If System.IO.File.Exists(FILE_NAME) = True Then
                Dim texto As New StreamReader(FILE_NAME)

                Dim Elems As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("textarea")
                For Each Elem As HtmlElement In Elems
                    If Elem.Name = "xhpc_message_text" Or Elem.Name = "xhpc_message" Then
                        Dim value2 As String = texto.ReadToEnd.Replace("[tituloGrupo]", WebBrowser1.DocumentTitle)
                        Dim value3 As String = value2.Replace("[codigoRandom]", CInt(Int((999999999 * Rnd()) + 1)))
                        Dim value4 As String = value3.Replace("[urlGrupo]", WebBrowser1.Url.ToString)
                        Dim value5 As String = value4.Replace("[dataAtual]", DateTime.Now.ToString("dd/MM/yyyy"))
                        Dim value6 As String = value5.Replace("[horaAtual]", DateTime.Now.ToString("HH:mm"))
                        'Elem.InnerHtml = value6
                        Elem.SetAttribute("value", value6)
                        Exit For
                    End If
                Next Elem
            End If
        Case 80
            For Each elem As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
                If elem.GetAttribute("type") = "submit" Then
                    If elem.InnerText = "Publicar" Then
                        elem.InvokeMember("click")
                    End If
                End If
            Next
        Case 85
            For Each element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
                If element.GetAttribute("className") = "_42ft _4jy0 _11b _4jy3 _4jy1 selected _51sy" Then
                    element.InvokeMember("click")
                End If
            Next
        Case 99
            If WebBrowser1.DocumentText.Contains("Publicar") Then
                If Label22.Text = "-------------" Then
                    Label22.Text = 1
                Else
                    Label22.Text = Label22.Text + 1
                End If
            End If

            FlushMemory()
            ProgressBarStatus.Value = 0
            postGrupo.Stop()
    End Select
End Sub

1 answer

2


I’d say 99% of the time someone wears one timer did not need it. A timer It should only be used when you really need something to run at each time interval. But most of the problems that need something to run are dependent on some specific event, something that happened and at that moment should call the application that needs to do something after the event happens, even if it is something outside the application. It is often possible to be notified that the event happened even in services outside the application.

I don’t think this is the main cause of the problem but the tip is that the application architecture is probably already wrong there.

Exception

If you feel a pain in your arm, what do you do? Cut your arm off? That’s what you’re doing in the code.

The first thing you need to fix is to stop swallowing exceptions. If an exception occurs, deal with it. Either fix the programming error that causes it, or perform some action that can recover from it, but never swallow it like you did here:

Try
    StartPostGrupos()
Catch ex As Exception

End Try

You will say that if you take this out you will start to make mistakes and the application will break. Great, then you will know where to start to fix the mistakes it has. Throwing mistakes under the carpet only causes more problems.

I talk about this in several answers here on the site. Read it all. Follow the links to learn how to handle exceptions in the right way. Even if it is not from VB.NET, the basis is the same. Start with links down, but don’t stop at them:

Memory consumption

You manipulate an object WebBrowser1 that was created elsewhere. He’s of a kind that consumes a lot of memory. I wonder if you’re not letting him live too long. And worse, you keep abandoning him alive and creating other instances whenever necessary. I can’t guarantee it, but if the pattern of the rest of the code matches the section shown, there’s a possibility you’re doing this without realizing it. But it may not be. Lucky, no?

Dim texto As New StreamReader(FILE_NAME). Where are you closing this stream? Nowhere. And even if it was, this way there could be a leak if an exception occurred. Study the command Using to prevent these leaks. With it you prevent them from occurring even if an exception occurs.

Using texto As New StreamReader(FILE_NAME)
    'faz tudo o que precisa com esse stream aqui
End Using

Race condition

The code If File.Exists(imgGroupsDir & imgGroupsName) Then is not causing the problem reported in the question, but has a potential to cause a running condition. The file may exist at this time, but soon after it may cease to exist and then your application will generate an error without you knowing why. The correct is to try to access the file and treat the error if something happens. If you keep doing things like this, you’ll get in trouble eventually and you won’t even know why.

Other small big problems

The code If WebBrowser1.DocumentText.Contains("Iniciar discussão") = True Then will not cause problems but compare a boolean expression with True is unnecessary. I say this just so you learn to better understand what you are using and know when you need to use something or not. Without understanding the whole functioning of the language, the libraries used and its application, it is difficult to produce a code that solves any problem correctly. It would have been better if you had written If WebBrowser1.DocumentText.Contains("Iniciar discussão") Then.

Nor will I get into the merit that this is not suitable to do parser html.

Take advantage and try to standardize variable names, it is easier to read and understand the code.

This progress bar is really weird, but let it go.

The code calls out other codes and certainly has other parts running that may also be creating more memory leaks.

Under normal conditions I wouldn’t worry about this: selecionarIMG.Start(). But since this code is full of problems, I don’t know if this is getting connected unintentionally. Nowhere is there a Stop() in it. I don’t know what problem this can cause but consuming excess memory is one of the possibilities.

I’m really scared of what this is: FlushMemory(). This is probably firing the GC manually and causing more problem than solution. Then you can explain what this is, but I almost guarantee it shouldn’t be there.

postGrupo.Stop() should not be causing leakage but something loose so also gives me fear. The problem is that it seems design bad and should be spread throughout the application.

In this small stretch I have already found several errors, imagine how many others should exist in the rest of the application. And perhaps the same critical error must be in another part not shown. That’s why the question was initially closed, because it would probably only solve your problem by analyzing all your code and redoing your entire application.

I didn’t even mention that the code is using events and this can cause leaks in some situations when the publisher survives longer than the subscriber. You may be right. Let’s hope.

I don’t know if I’ve seen everything that could be causing a leak in this section. But I repeat that this is just the tip of iceberg. I think you’ve helped.

  • It’s really what you wrote is a great comment, and little opportunity to read something like that... in relation to what you reported on Webbrowser, which is always running, after using a command, go into pages, check pages and etc, how would you maybe clear his cache, or there’s nothing to it? thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.