| This page has broken markup.|
If you fix this problem, please remove this banner.
You may have noticed that the function does not have the ability to accept data as arguments. This is because of the AddressOf (there's no way to send arguments). Heres the way around it. We are going to adapt that function to find any number times 2, and put the result in an array instead of a listbox.
But to do this, we need encapsulate it in a class. This is the work around part. Because the function call for threading can't directly pass arguments, we use a class to transfer data around.
Public Class FillClass
Private intValue As Int32 Private intReturn(99) As Int32 Private intMultiplier As Int32
Public WriteOnly Property Value() Set(ByVal Value As Int32) intValue = Value End Set End Property
Public WriteOnly Property Multiplier() Set(ByVal Value As Int32) intMultiplier = Value End Set End Property
Public ReadOnly Property Return() As Int32() Get Return = intReturn End Get End Property
Public ReadOnly Property ReturnIndex(ByVal Index As Int32) Get Return = intReturn(index) End Get End Property
Public Function Fill() Dim i As Int32 Dim current As Int32 current = intValue For i = 0 To 100 intReturn(i) = current current *= intMultiplier Next End Function
So we have a class that has two internal variables, intValue and intReturn. These have properties that allow objects outside of the class to access them, and one to modify the multiplier. There is also another property to return the value from a specified index (used later). There is also the Fill function, which has been modified.
Here is how we use the class:
Dim oThread As System.Threading.Thread
Dim oFill As New FillClass
oThread = New Thread(AddressOf oFill.Fill)
oFill.Value = 3 oFill.Multiplier = 2
Here, we modified created a new instance of the ))FillClass((, then set oThread equal to the AddressOf the oFill.Fill function. Then we used the public property to set the data, then finally started the thread. Notice though that we did not use the Return property after calling start. Here is where you will have to start thinking in a multithreaded mindset. Theres no guarantee that the thread will be finished right after we call it, so using the Return property would be pointless. This is where "Synchronization" comes in. There are several ways, but the easiest way to determine when a thread is completed is an event.
Go back to the ))FillClass(( and add this line to the declarations:
Public Event Done(ByVal intReturn() As Int32)
and this line to the end of the function:
This event will fire when the function is done, and also passes the return value. Now, you have two different ways to retrieve the return value; the property or the event. Another method is to use Thread.Join.