PaulWill PaulWill - 3 months ago 14
Vb.net Question

Issue with callback garbage collected

I am receiving an error "A callback was made on a garbage collected delegate of type" using this code, but I cant seem to find the solution.

<DllImport("winmm.dll")>
Private Shared Function timeSetEvent(delay As Integer, resolution As Integer, handler As TimerEventHandler, user As IntPtr, eventType As Integer) As Integer
End Function

<DllImport("winmm.dll")>
Private Shared Function timeBeginPeriod(millisecond As Integer) As Integer
End Function

Private Sub OnLoadit()
timeBeginPeriod(1)
Dim mHandler As New TimerEventHandler(AddressOf TimerCallback)
Dim mTimerId As Integer = timeSetEvent(4, 0, mHandler, IntPtr.Zero, 1)
End Sub

Private Delegate Sub TimerEventHandler(id As Integer, msg As Integer, user As IntPtr, dw1 As Integer, dw2 As Integer)
Private Sub TimerCallback(id As Integer, msg As Integer, user As IntPtr, dw1 As Integer, dw2 As Integer)
'my function code here
End Sub

Answer

Try chaning mHandler into a class member (e.g. a private field) as currently it is scoped to the OnLoadit method so that after its execution mHandler can be collected via GC at the moment.

Comments