VB.NET Form.Show from another thread hanging form - vb.net

I have a series of methods being called for my networking code. An event gets fired from the networking thread. Inside this event, which I've hooked into from a singleton class, I route messages to form level methods which they register on form load to handle certain messages they care about. Inside of these form message hooks I need to close the current form (which I was able to do) but also show a different one (which is giving me the trouble).
The new form sort of shows but it's hanging/not updating. I'm sure this has something to do with that form because it's .Show() was basically called from another thread (sort of) doesn't have a message loop, but I'm not sure how else to solve this. The network message that gets received indicates on the client machine what forms to close and show.
The flow might be confusing so I'll try better to explain.
Login form attaches user defined functions inside that form to a singleton class list of messages. For example when a message called LOGIN_STATUS is fired I assign a function from the Login form to a list defined in this singleton class.
The singleton class has the network class defined in it which actually runs on another thread, but this is all handled inside the class. In the private ctor I subscribe to the OnData event of this network class.
When OnData gets fired from the network class to the singleton class it passes to it the type of data. I loop through the list of function pointers to see if any of them are linked to LOGIN_STATUS and if so call them. This will call the Login forms function. Inside that function I need to close the Login form and open the Lobby form. That's when the Lobby form shows, but is hung up and not updating.
Hope that makes sense.
This is all being done in VB.NET where I have the "close when last form closed" setting on which is what I want. VB.NET also makes it easier to manage forms since I can just for formname.Show() instead of having to keep a list of the forms and manage them myself like in C# so if that's still possible with the solution that would be ideal.

If you want to ensure all forms are created on the same thread, and hence the same message loop, use the main from's Invoke method. The Form.Invoke and Form.BeginInvoke methods cause the code to run from the form's message loop. BeginInvoke allows the event calling thread to return immediately, where-as Invoke blocks the event thread until the method is complete. It depends how time sensitive your code is.
Private Sub OpenFormEvent(sender As Object, e As EventArgs)
If MainForm.InvokeRequired Then
Dim args As Object() = {sender, e}
MainForm.BeginInvoke(New EventHandler(AddressOf OpenFormEvent), args)
Else
Dim SecondForm As New Form()
SecondForm.Show()
End If
End Sub

Related

Issues with Event Handlers not being removed (using RemoveHandler) when sender is part of another class

I have a system where a Class of "Automation Providers" is working with some Control objects to provide some advanced monitoring functionality to them (by dynamically monitoring events).
A part of my code; A class called Automation_Provider contains a function called Browser_Navigate that takes in a reference to a System.Windows.Forms.WebBrowser instance and performs a .Navigate operation with a URL.
The special functionality it provides is that it sets an Event Handler to the Browser.DocumentCompleted to perform some actions when the event is raised.
This part actually works. What doesn't work, is I'm trying to dynamically remove the handler that causes the Subroutine to be called in the first place, but it doesn't seem to remove the Handler and if I try to call the function again, it fires twice.
The code looks like this:
Public Class Automation_Functions
Public Function Browser_Navigate(ByRef Browser As WebBrowser, ByVal Address As String) As Function_Status
'-----------------------------------------------------------------------------------
' A bunch of URL checks are performed here to make sure the "Address" is a valid URL
'-----------------------------------------------------------------------------------
AddHandler Browser.DocumentCompleted, AddressOf Browser_Navigation_Callback
Browser.Navigate(Address)
End Function
Private Sub Browser_Navigation_Callback(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'Get the browser object from the sender and remove the handler that initially called this function
Dim Browser As WebBrowser = CType(sender, WebBrowser)
RemoveHandler Browser.DocumentCompleted, AddressOf Browser_Navigation_Callback
'------------------------------------------------------------------------------------------
' A bunch of operations are performed here related to telling the caller of the original
' function about the performance of the web page - stuff like load time, etc.
'------------------------------------------------------------------------------------------
End Sub
End Class
However the Past Handlers are never actually removed from the Browser_Navigation_Callback function - I know this because calling the Browser_Navigate function a second time results in Browser_Navigation_Callback function being called twice, then if you call it a third time, it gets called Three times! - The Handlers just compound on top of each other since they never actually get removed.
I've been unable to find any reason as to why this is happening - I'm assuming it might have something to do with the fact that the WebBrowser object is actually inside of another class and casting the sender as a WebBrowser object doesn't refer it back to the original WebBrowser instance, but creates a new instance. However I have no idea on how to confirm that this is actually what is happening since I can't really see the attached event handlers in debug mode.
Other than that - this code should be working. Any help would be appreciated!
One of the features of VB when Option Strict is not set is that it will use "relaxed delegate conversion". This means that when a delegate argument does not exactly match the required signature but is compatible with it, VB will automagically insert an anonymous wrapper that converts from the provided delegate to the required signature.
This has a negative interaction with AddHandler and RemoveHandler. VB creates a new anonymous wrapper on each call, and each instance is distinct. As a practical matter, that means that it is impossible to remove a handler that has been added when relaxed delegate conversion is used.
With Option Strict on, relaxed delegate conversion is disabled, so it turns into a compiler error when the delegate argument does not exactly match the required signature. I have not found an individual compiler switch that will turn off relaxed delegate conversion, so the only way to deal with this is to turn on Option Strict for the file.

How should you reload a form and have it re-initialize?

A older application loads some forms using implicit instances:
form2.showdialog()
Sometime between VS2008 32-bit and VS2013 64-bit, the forms stopped being initialized when they are reloaded. For example, if you load a form, close the form (using the Close method), and load the form again, the classes and controls (and, I assume, the form) are not initialized as new instances.
Re-initialization can be accomplished by putting me.dispose() in the FormClosed event, or by using an explicit instance of the form:
Using frm As New Form2
frm.ShowDialog()
End Using
Is there a good reason to use one of these methods over the other, or is there another method that should be used to cause a form to be initialized when it is reloaded?
Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used (your case it is), or the form is never shown at all, you must call Dispose yourself within your application. You can also handle the dispose by moving it from the designer file into the code file and handle things there as well.
On the other hand, Using statement typically makes your application safer to maintain and less prone to deadlocks and other misbehavior related to the lifecycle of the resource. I would stick by using this approach.
Also you cant put Me.Dispose in the Form Closed event (possible issues). If your using ShowDialog it will fail as it will dispose your objects first, if you need them they are gone.
Here's more on dispose: https://msdn.microsoft.com/en-us/library/aw58wzka(v=vs.110).aspx
The Form object and its child controls are not automatically disposed when you display the form with ShowDialog(). That sounds pretty quirky but this was done for a very good reason. After ShowDialog returns DialogResult.OK, you are normally going to obtain the dialog results. What nobody likes is that failing because of a ObjectDisposedException. Which would be likely to occur since the dialog results are often stored in controls.
You should always use the Using statement to ensure the form object and all of its controls are disposed.
A possible corner case is intentionally not disposing it because you like the redisplay the dialog with the original entered values. Which is not completely wrong, it is however a very expensive way to preserve those values. Those undisposed window objects cost an arm and a leg in system resources.
Pretty clear explanation from MSDN
Unlike non-modal forms, the Close method is not called by the .NET
Framework when the user clicks the close form button of a dialog box
or sets the value of the DialogResult property. Instead the form is
hidden and can be shown again without creating a new instance of the
dialog box. Because a form displayed as a dialog box is hidden instead
of closed, you must call the Dispose method of the form when the form
is no longer needed by your application.
When ShowDialog() called and closed, instance of the form will remain in the memory, and can be used again, for example get a result from some public property.
If you not using anymore this form, you need to call Dispose method to dispose form and form's controls
Dim myform As New MyDialogForm()
myform.ShowDialog()
Dim result As Object = myForm.SelectedResult()
myform.Dispose() 'need to call manually, if instance not used anymore
When you use Using keyword then Dispose method will be executed automatically at the end of the Using block
Dim result As Object
Using myform As New MyDialogForm()
myform.ShowDialog()
result = myForm.SelectedResult()
End Using 'myform.Dispose will be called
Bottom line: Both methods doing a same things.
But Using block will call Dispose method automatically
P.S. Putting Me.Dispose in the FormClosed eventhandler then
- instance of the form will stay in the memory even form was closed
- and will work only until you tried using disposed controls again. If you will try to show disposed object then ObjectDisposedException will be thrown.
If you not using form anymore then Using block will be best method

What is the purpose of calling Invoke from the specific control that's affected?

Say I've got the following sub that simply adds passed items to a ListView control:
Private Sub AddListItem(ByVal item As ListViewItem)
UIList.Items.Add(item)
End Sub
And I use that from a BackgroundWorker thread, like so:
UIList.BeginInvoke(Sub() AddListItem(lvItem))
Well quite by accident I've just discovered that it doesn't seem to matter which control is used to call the Invoke\BeginInvoke method, or even if I omit a control altogether and just call the method directly – which I assume just uses Me.<Method> behind the scenes – it doesn't seem to matter. The code still works.
So, is using the affected control to call the method just a way to make following the code easier? What, if any, are the other advantages? And are there certain pitfalls one needs to be aware of when using a different control?
Using ILSpy and digging down the Control.Invoke method, an excerpt is
...
UnsafeNativeMethods.PostMessage(
new HandleRef(this, this.Handle),
Control.threadCallbackMessage,
IntPtr.Zero,
IntPtr.Zero);
...
In addition, MSDN states:
The Invoke method searches up the control's parent chain until it
finds a control or form that has a window handle if the current
control's underlying window handle does not exist yet. If no
appropriate handle can be found, the Invoke method will throw an
exception. Exceptions that are raised during the call will be
propagated back to the caller.
So usually it shouldn't matter which control you post to.
Personally, I use the "nearest" control I can get to call the Invoke method.

Update UI form from worker thread

I am new to multi-threading in VB.NET and have come across a problem whereby I am wanting to append text to a text box on a form from a service thread running in the background.
The application I am developing is a client/server listener, I have been able to get the client and server PC's to talk with each other (confirmed through MsgBox), however I am now struggling to get the service thread on the server to append the text to the textbox, nothing vissible occurs.
I have a form named testDebug which calls a class (RemoteSupport), this class does all the handshake tasks and updates the textbox with the connection data.
Can anyone identify where I am going wrong and point me in the right direction?
The following is the code I have:
The form has a textbox named txtOutput, the following is from the remoteSupport class
Dim outMessage As String = (encoder.GetString(message, 0, bytesRead))
MsgBox(outMessage, MsgBoxStyle.Information, "MEssage Received")
If outMessage IsNot Nothing Then
If testDebug.InvokeRequired Then
' have the UI thread call this method for us
testDebug.Invoke(New UpdateUIDelegate(AddressOf HandleClientComm), New Object() {outMessage}) '
Else
testDebug.txtOutput.AppendText(outMessage)
End If
'RaiseEvent MessageReceived(outMessage) // a previous attempt to use custom events
End If
I am not sure if the invoke method is the ideal solution or if custom events are, I have spent some time on trying to get custom events to work, but these didnt work either.
// In the RemoteSupport class
Public Delegate Sub MessageReceivedHandler(ByVal message As String)
Public Shared Event MessageReceived As MessageReceivedHandler
// Located throughout the RemoteSupport class where debug information is required.
RaiseEvent MessageReceived(outMessage)
// Located in the code-behind of the form
Private Sub Message_Received(ByVal message As String)
testDebugOutput(message) // this is a function I have created
// to append the text to the text box
End Sub
The code supplied has been cut down so if there is anything else that you want to see or any questions please let me know.
Thanks for your assistance.
EDIT: I have uploaded the two VB files (form and class) to my site, I would appreciate it if someone could have a look at it to help me with identifying the problem with the UI not updating.
I have tried a few other things but nothing seems to be updating the UI once the worker thread has started.
Form: mulholland.it/testDebug.vb.txt
Class: mulholland.it/remoteSupport.vb.txt
Thanks for your assistance.
Matt
I have a form named testDebug...
If testDebug.InvokeRequired Then
This is a classic trap in VB.NET programming. Set a breakpoint on the If statement. Notice how it returns False, even though you know that the code is running on another thread?
InvokeRequired is an instance property of a Form. But testDebug is a class name, not a reference to an instance of a form of type testDebug. That this is possible in VB.NET has gotten a lot of VB.NET programmers in deep trouble. It is an anachronism carried over from VB6. It completely falls apart and blows up in your face when you do this in a thread. You'll get a new instance of the form, instead of the one that the user is looking at. One that isn't visible because its Show() was never called. And otherwise dead as a doornail since the thread isn't running a message loop.
I answered this question several times already, with the recommended fix. I'll just refer you to them rather than rehashing it here:
Form is not updating, after custom class event is fired
Accessing controls between forms
The Delegate method is likely the way you want to go, but I don't see the declaration of the UpdateUIDelegate anywhere
I believe your code should look something like this (assuming you have a reference to the testdebug form local to your remotesupport class
Dim outMessage As String = (encoder.GetString(message, 0, bytesRead))
MsgBox(outMessage, MsgBoxStyle.Information, "MEssage Received")
If outMessage IsNot Nothing Then
If testDebug.InvokeRequired Then
' have the UI thread call this method for us
testDebug.Invoke(New MessageReceivedHandler(AddressOf Testdebug.Message_Received), New Object() {outMessage})
Else
testDebug.txtOutput.AppendText(outMessage)
End If
end if

Force multi-threaded VB.NET class to display results on a single form

I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.
I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.
Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.
MORE INFORMATION: I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?
I'm going to pull my hair out! This can't be that hard!
SOLUTION: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:
Public Sub New()
If My.Application.OpenForms(0).Equals(Me) Then
Me.IsFirstForm = True
End If
End Sub
Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):
Public Sub EventHandler()
If Not IsFirstForm Then
Dim f As Form1 = My.Application.OpenForms(0)
f.EventHandler()
Me.Close()
ElseIf InvokeRequired Then
Me.Invoke(New HandlerDelegate(AddressOf EventHandler))
Else
' Do your event handling code '
End If
End Sub
First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!
Again, thanks for all the help - this was going to drive me nuts!
I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.
Edit after OP changed question:
A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a new instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.
You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms:
Dim main As Form1 = CType(Application.OpenForms(0), Form1)
if (main.InvokeRequired)
' etc...
Use Control.InvokeRequired to determine if you're on the proper thread, then use Control.Invoke if you're not.
You should look at the documentation for the Invoke method on the Form. It will allow you to make the code that updates the form run on the thread that owns the form, (which it must do, Windows forms are not thread safe).
Something like
Private Delegate Sub UpdateStatusDelegate(ByVal newStatus as String)
Public sub UpdateStatus(ByVal newStatus as String)
If Me.InvokeRequired Then
Dim d As New UpdateStatusDelegate(AddressOf UpdateStatus)
Me.Invoke(d,new Object() {newStatus})
Else
'Update the form status
End If
If you provide some sample code I would be happy to provide a more tailored example.
Edit after OP said they are using InvokeRequired.
Before calling InvokeRequired, check that the form handle has been created, there is a HandleCreated property I belive. InvokeRequired always returns false if the control doesn't currently have a handle, this would then mean the code is not thread safe even though you have done the right thing to make it so. Update your question when you find out. Some sample code would be helpful too.
in c# it looks like this:
private EventHandler StatusHandler = new EventHandler(eventHandlerCode)
void eventHandlerCode(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(StatusHandler, sender, e);
}
else
{
//do work
}
}