0

I'm making a class that creates a new instance of an already existing form every time "New" is called. I'm implementing this in a Class Library, the class library has a "WndClass" (Class) and a "MainWindow" (Form). The problem is I get the above error whenever I try to close the window by InsWindow.Close

Here's the code:

Public Class WndClass
   Public Shared WindowCount As Integer
   Private InsWindow As MainWindow

Public Sub New()
    WindowCount += 1
    InsWindow = New MainWindow
    InsWindow.Show()
End Sub

'.... Some window manipulation functions

Protected Overrides Sub Finalize()
    WindowCount -= 1
    InsWindow.Close()
    InsWindow.Dispose()
    MyBase.Finalize()
End Sub
End Class

I'm fairly new to the language so I decided to go experimenting and coding random ideas that come to my mind.

EDIT: I've read up some similar but not necessarily the same problems, and some of them said delegates are what solved the issues, can someone explain how can I use it to solve this?

  • Have you tried this [link](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the)? – Edper Oct 23 '13 at 10:13
  • By the time `Finalize` is being called, it's far too late for code inside such a method to be talking to other managed objects in a sensible fashion. It's only intended for use in cleaning up unmanaged resources (such as ones allocated via P/Invoke calls). I can't offer any more specific advise unless you can say why you thought `Finalize` was the right place to put this code. – Damien_The_Unbeliever Oct 23 '13 at 10:52

1 Answers1

0

Without knowing the error, I can only take a shot in the dark...

The fact that you mentioned delegates, I would recommend trying the following:

Protected Overrides Sub Finalize()

    If Me.InvokeRequired Then
        Me.Invoke(New MethodInvoker(AddressOf Me.Finalize))
    Else
        WindowCount -= 1
        InsWindow.Close()
        InsWindow.Dispose()
        MyBase.Finalize()
    End If

End Sub

Delegates are used when you need to change the thread that the code is running on (ie: you need to get back to the UI thread).

Normally you'd have to create a delegate (ie: Private Delegate Sub Test(val1 As String, val2 As String, etc..)) then invoke the delegate while passing it the address of the method you wish to invoke (Note: the variables of the delegate must match the method being called).

If there are no variables being passed to the method, you can invoke the MethodInvoker like so Me.Invoke(New MethodInvoker(AddressOf Me.Foo))...

Keep in mind it's good practice to always check if an invoke is required by checking Me.InvokeRequired

Grahamvs
  • 669
  • 6
  • 16