Okay, if you're familiar with delegates, this is a breeze... if not, this is going to take some getting your head around.
If you want to post data to the main thread from another, then you have to post through a delegate method - think of a delegate method as a placeholder for the memory address of a method. We put the address of the method we wish to run into the delegate which then sits and waits to be called. At whatever point the delegate is called - it fires whatever method sits at the address stored in its buffer.
It's been a while since I had to do this, but the following code is close enough to point you in the right direction...
VB.NET
- Public Delegate Sub SetLabelTextDelegate(ByVal LabelObject As Label, ByVal Value As String)
-
-
Public Sub SetLabelText(ByVal LabelObject As Label, ByVal Value As String)
-
-
If LabelObject.InvokeRequired Then
-
Dim dlg As New SetLabelTextDelegate(AddressOf SetLabelText)
-
dlg.Invoke(LabelObject, Value)
-
Else
-
LabelObject.Text = Value
-
End If
-
-
End Sub
C#
- public delegate void SetLabelTextDelegate(Label LabelObject, string Value);
-
-
public void SetLabelText(Label LabelObject, string Value)
-
{
-
if (LabelObject.InvokeRequired) {
-
SetLabelTextDelegate dlg = new SetLabelTextDelegate(SetLabelText);
-
dlg.Invoke(LabelObject, Value);
-
}
-
else {
-
LabelObject.Text = Value;
-
}
-
}
So where you would normally make a call like Label1.Text = "Stuff", you would now make the following call: SetLabelText(MyLabelObject, "Text to put in my label").
This will now post text from the secondary thread properly... in my applications, I usually create this pattern for each type of object I have on screen that will required updating from any thread and all calls to set the values will go through the SetxxxValue method (regardless of which thread I'm posting from, for consistency), which will pass the object to be updated and the text to put into it.