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

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
}
}

Related

Datagridviewss and Threads

I want to update a datagridview from a thread using VB.
I have tried two approaches so far, but clearly I am missing something. The two methods are:
If Control.invokeRequired Then
Control.Invoke(Sub() Control.rows.add(Event*Date, Event*Details))
And I have tried:
If Control.InvokeRequired then
Control.Invoke(New Addrow(AddressOf Form1.AddToDatatable), New Object() {Data_row})
Where
Public Delegate Sub Addrow(ByVal Data_row As DataRow)
Public Sub AddToDatatable(ByVal Data_row As DataRow)
Data_table.Rows.Add(Data_row)
Daily_Log.Refresh()
End Sub
It appears that you have a DataTable bound to a DataGridView. In that case, you need to add the data to the DataTable. InvokeRequired and Invoke are instance members of the Control class, so need to be accessed via a control reference. If you know the code is being executed on a secondary thread then using InvokeRequired is pointless. I suspect that your code should be like this:
myDataGridView.Invoke(Sub() myDataTable.Rows.Add(someValue, someOtherValue))
Your would only need to use InvokeRequired if the code is in a method that might be executed on the UI thread or a secondary thread. For instance, you might do this:
Private Sub AddRow(column1Value As Object, column2Value As Object)
If myDataGridView.InvokeRequired Then
myDataGridView.Invoke(New Action(Of Object, Object)(AddressOf AddRow), column1Value, column2Value)
Else
myDataTable.Rows.Add(column1Value, column2Value)
End If
End Sub
You can then just call that method anywhere and it will handle the rest. You can do this on a secondary thread:
AddRow(someValue, someOtherValue)
On that call, InvokeRequired will be True, so a delegate will be created for the same AddRow method nad passed to Invoke, along with the parameter values. Invoke will cross the thread boundary and invoke AddRow a second time. This time InvokeRequired will be False, so the row will be added to the DataTable.
Thank you everybody for your suggestions. I wrote my question in abject frustration on Thursday after spending a day reading forums trying to find out what was going on. Friday afternoon I eventually worked it out.
Two things led to me finding a solution.
I could not work out why invokerequired was always returning false. I initially assumed this was because I was running in debug to watch the code. In frustration I removed the invokerequired and let the code go to the invoke. This was the best thing I could have done even though it threw an error. Something about the form event not created
This made me wonder about the form and the control so I added some debug code on isdisposed and eventcreated. Both returned false.
Yet the form was sitting in front of my eyes waiting for data...
It then occurred to me that maybe, just maybe I was not able to address the displayed form at all from the thread.
In desperation I decided to add the form to the thread initiation and receive the form as a parameter when the thread initiated.
Omg! It worked. Invokerequired suddenly turned true and the invoke worked without error and data started appearing on my form, cracked it!
They say hard learning is not forgotten quickly, and I doubt I'll forget this quickly.
In summary when initiating the thread, pass the live form as the sole parameter and in your thread reference the passed form, not the from directly... Grrr.
I hope me posting this helps save someone else from tearing their hair out.

sub functions vs event, what is the difference?

I went through events in Vb.net and i found they are really an amazing feature..but still confused about how to use them effectively.
The real doubt is that the functions and sub could be effective alternative for events. Whatever i do with events i can manage to do it via functions and methods. Wherever there is Raisevent, i can substitute it with a function or procesure. so then, what is the real benefit of events and in which cases i can use them instead of functions and procedures?
Let's see if you understand it with an example. You have the Button control. It defines a lot of events (Click,MouseDown,Keypress...). When you put a button in a Form, you decide there what are the events you want to manage. So in the form you can do something when a button is clicked, or not doing anything.
Imagine if this was done with regular methods. In that case, the button should have a reference to the form where the button is, and the form should have a Click method, is it using it or not.
The event driven programing makes very easy to define some Events to signal when something happens in a class, and is the class that creates the instance the one that decides if that event is relevant or not.
thank you for clarification, I got the point. The point I Missed was that : event is fired in the same class, but execution is done in a different class.
I mean, when I define a class, I can put RaiseEvent somewhere to recognize something, but I correlate the event with a sub in a different class.
so, in such a class called Wallet I can put a statement like :
If Dollars > 5 Then
RaiseEvent Above5()
End If
and in such different class called AllWallet :
Dim WithEvents myWallet as new Wallet
Sub myWallet_Above5() Handles myWallet.Above5
MsgBox("Dollars are more than 5")
End Sub
otherwise, I mean if events are fired in the same class they are defined in , the sub and functions can substitute events.
thanks to all

How to update a rich text box from a background worker using a delegate

Ok I'm pretty new to using threads but so far I've managed to get the following:
Private Delegate Sub dlgUpdateText(text as string)
Private Sub UpdateStatus(text as string)
If rtxStatus.InvokeRequired then
Dim dlg as new dlgUpdateText(AddressOf UpdateStatus)
Me.Invoke(dlg, text)
Else
rtxStatus.text = text
End If
End Sub
and from my Async BackgroundWorker I call
UpdateStatus("Some text")
which seems to work ok however in my original code (which generates errors because I'm updating the control from the wrong thread) I used the following code to append to the (rich)textbox:
rtxStatus.Select(rtxStatus.TextLength, 0)
rtxStatus.SelectionColor = Color.Red
rtxStatus.AppendText("Some error occurred gathering data")
My question is how should I modify my new code to allow me to do this rather than just replace the text? I have read several guides on using delegates but I'm still lost on a few points so I don't really know what's going on with the code I have.
Bonus questions (which probably serve best to show what needs explaining to me!):
What does the Delegate Sub actually do? It doesn't seem to serve any purpose other than hold the property (text) that was already passed to the main Sub (UpdateStatus)?
What is happening when Me.Invoke is called? Me is the current form so when I pass the Delegate Sub and the text where is it specified that the text should be passed to the rtxSTatus.Text property?
UpdateStatus runs in the main thread (?) and is called from one of the background worker threads so why is the Invoke even necessary or is the UpdateStatus Sub run under the background thread that called it? When I altered the text that is applied in the Else statement to see which was run it seems that Invoke is never used to change the text in the box.
Any help would be really appreciated, I'm completely baffled by this - thanks!
Rather than creating a delegate I would suggest using the existing methods offered from a backgroundworker. The backgroundworker provides two methods to access the main thread:
The ProgressChanged event to update the main thread during backgroundworker processing and the RunWorkerCompleted event to update the main thread once the backgroundworker process is complete.
You can find this information and how to implement it from the following link:
http://msdn.microsoft.com/en-us/library/ywkkz4s1.aspx

VB.NET Form.Show from another thread hanging form

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

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