How do I make a property/variable common to multiple asynchronous threads?
Posted on 2006-10-27
I have an application that is using background workers and an asynchronous socket system.
on my form, I have a class that I created that stores my client socket object and it triggers events when data comes in, etc.
I also have labels, properties, and variables populate as communication occurs.
I have a variable that is global to my form called "Response"
I have another global variable called ReceiveTimeout
I have a method called "send_data"
I have a method called "Data_Received" which is the handler of my socket object receive event.
in my send method I do this:
Response = ""
If System.Environment.TickCount - ReceiveTimeout > 30000 Then Exit Do
if Response = "Done" then exit do
Pretty simple.... send a command to the server and wait for it to reply with "done" or time out after 30 seconds.
if my Data_Received event, I have this:
if IncommingData.StartsWith("***Progress:") then
' we got a progress report from the server, so update the progress label with the message.
' Reset the time out so that we don't end prematurely
ReceiveTimeout = System.Environment.TickCount
' We got a command response from the server
Response = IncommingData
And my update status routine:
Private Delegate Sub UpdateStatusDelegate(ByVal Text As String)
Private Sub UpdateStatus(ByVal Text As String)
If Me.InvokeRequired Then
Dim d As New UpdateStatusDelegate(AddressOf UpdateStatus)
d = Nothing
lblStatus.Text = Text
So, the plan was this. Send a command through the socket port, and asynchronously wait for a command to come it, or time out after 30 seconds.
Once the command comes into the buffer, the object will raise the event that will populate the response variable and thus, when data_received routine finishs executing, then send method will see the change and exit the do loop without timing out or error.
The PROBLEM is that the datarecieve event fires, and populates the response variable just fine. But the send method thread doesn't read it. The response value in the send method stays blank while the value of response in the data received method is that of the command response. At the same time, when I try to update the status of the label, the text value in the datareceived method is what I set it to, but in the send method the label text stays blank.
it is almost as if my global variables and properties and controls have duplicated for the alternative thread and are discarded when the setting thread is finished.
How can I get my data from one thread to the other?
I am using VS 2005