1

I want to generate a image when a event is triggered. When the event is trigger again and the image is still generating. It will abort the generation and generate again. But my code will cause a memory leak. The application's memory usage will grow up rapidly. Does anyone know what's wrong?

edit: I put GC.Collect() after the thread is aborted. But It's no use.

edit: The leak speed will become slower when timer's interval sets to a big number(like 2000).

Here's my code:

Public Class Form1
    Dim a As Threading.Thread
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Main()
    End Sub

    Sub Main()
        If a IsNot Nothing AndAlso a.IsAlive Then
            a.Abort()
            a.Join()
            'GC.Collect()   'not working
            'GC.WaitForPendingFinalizers()   'not working
        End If
        a = New Threading.Thread(AddressOf func)
        a.Start()
    End Sub

    Sub func()
        Dim newObj As Class1 = Nothing
        Try
            newObj = New Class1
        Catch ex As Threading.ThreadAbortException
            newObj?.Dispose()
        End Try
    End Sub
End Class

Public Class Class1
    Implements IDisposable
    Dim Img As New Bitmap(4095, 4095)

    Public Sub Dispose() Implements IDisposable.Dispose
        Img?.Dispose()
    End Sub
End Class
czxinc
  • 11
  • 2
  • 4
    Use the [memory profiler](https://learn.microsoft.com/en-us/visualstudio/profiling/memory-usage-without-debugging2?view=vs-2022#memory-usage-snapshot-reports) built into VS so you can see what object is getting leaked. Usually it is bitmaps btw, small managed object that doesn't put any pressure on the GC, but lots of unmanaged memory. – Hans Passant Jan 14 '23 at 19:49
  • I have tried. But I couldn't find any leak information about bitmap. – czxinc Jan 15 '23 at 08:33
  • Do you see the same result [in the release build](https://stackoverflow.com/a/17131389/11683)? – GSerg Jan 15 '23 at 09:14
  • @GSerg I try `GC.WaitForPendingFinalizers()` and switch to the release build on this article. It's not working. – czxinc Jan 15 '23 at 17:59
  • This is obviously not your full code. Would it be possible to instead of creating a whole new thread along with a new bitmap, that you instead reset the bitmap to an "erased" state and restart the looping mechanism that draws it? At any rate `Thread.Abort()` is pretty much NEVER the correct approach as it's been [deprecated and obsolete](https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/5.0/thread-abort-obsolete) for a very long time. – Idle_Mind Jan 15 '23 at 19:43
  • @Idle_Mind I create a new project. It has the same problem. I post all codes except winform designer code. My project use .net 4.8, it doesn't say `Thread.Abort()` is been deprecated and obsolete. The "erased" state is good. I will try it. – czxinc Jan 16 '23 at 03:45

0 Answers0