Passing data to a thread

J

Jerry Spence1

I have seen the following example of passing data to a thread:

Class ThreadData
Public Id As Integer
Public Msg As String
Public Done As Boolean
'
The entry point for the thread

Sub DoTheTask()
For i As Integer = 1 To 10
' Show that the thread received the correct values.
Console.WriteLine("{0} (Thread ID = {1})", msg, id)
' Wait for 0.2 second.
Thread.Sleep(200)
Next
' Let the main thread know that this thread has completed.
Done = True
End Sub
End Class


I am a little puzzled about the use of a public variable here and the
possibilities of it being overwritten by another thread. It raised a
question in my mind about the scope of public variables. Are they public
throughout the whole project or just within a class?

-Jerry
 
K

Ken Tucker [MVP]

Hi,

They are public to the class. If you have several instances of
the class each will have there own public variables. In case you were
wondering the synclock statement will help prevent a variable from being
overwritten.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmsynclock.asp

Ken
-------------------
I have seen the following example of passing data to a thread:

Class ThreadData
Public Id As Integer
Public Msg As String
Public Done As Boolean
'
The entry point for the thread

Sub DoTheTask()
For i As Integer = 1 To 10
' Show that the thread received the correct values.
Console.WriteLine("{0} (Thread ID = {1})", msg, id)
' Wait for 0.2 second.
Thread.Sleep(200)
Next
' Let the main thread know that this thread has completed.
Done = True
End Sub
End Class


I am a little puzzled about the use of a public variable here and the
possibilities of it being overwritten by another thread. It raised a
question in my mind about the scope of public variables. Are they public
throughout the whole project or just within a class?

-Jerry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top