how to decrease CPU usage when using multiple threads VB.net? - vb.net

I am using vb.net , .NetFramework 2.0 .
My application gets live stock prices from google and updates stocks in database each 10 seconds.
I get this code for multithreading. When application starts updating stocks in database(about 200 stocks) , the update takes up to 3 seconds but it increase CPU usage from 10 % to 70 % or 80 %.
What is the best way to to update database without getting CPU increase to high level?
I observed that all threads works at the same time. how to make each thread wait until the second ends?
This is my code. The problem is in function updateThreaded2().
Please I need quick help. Thanks
Public Function Update2(ByVal l As SortableBindingList(Of NewStockList)) As Long
res = 0
UThread = New System.Threading.Thread(AddressOf UpdateThreaded2)
If Me.URunning = True Then
Else
Try
Me.URunning = True
Interlocked.Exchange(Me.UCount, 0) 'threadsafe method of assigning static value
Interlocked.Exchange(Me.UDone, 0) 'threadsafe method of assigning static value
UThread.Priority = Threading.ThreadPriority.BelowNormal
UThread.IsBackground = True
UThread.Start(l)
Return 0
Catch ex As Exception
End Try
End If
End Function
Private Sub UpdateThreaded2(ByVal l As SortableBindingList(Of NewStockList))
Dim i As Integer = 0
Dim threadcount As Integer = Math.Min(Me.MaxThreads, Me.Stocks.Count)
Dim threads(threadcount - 1) As SUTC
Try
While i < Me.Stocks.Count
For j As Integer = 0 To threadcount - 1
If threads(j) Is Nothing Then
If i < Me.Stocks.Count Then
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
ElseIf threads(j).UpdateState = 0 Then
If i < Me.Stocks.Count Then
SecUpd(j) = Me.Stocks(i).symbol
threads(j) = New SUTC(Me.Stocks(i), Me.DefaultService, AdjustSplits, Use20Minutes, l)
threads(j).Thread.Priority = Threading.ThreadPriority.BelowNormal
threads(j).Thread.IsBackground = True
threads(j).Thread.Start()
i += 1
End If
End If
Next
Dim running As Boolean = True
While running
For j As Integer = 0 To threadcount - 1
If threads(j).UpdateState = 0 Then
Thread.Sleep(10)
running = False
SecUpd(j) = ""
Interlocked.Increment(UDone) 'threadsafe method of incrementing a variable by 1
Interlocked.Exchange(UCount, UCount + threads(j).UpdateCount) 'Threadsafe method for assigning a value
End If
Next
End While
End While
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
Thread.Sleep(10)
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
Me.URunning = False
Catch ex As System.Threading.ThreadAbortException 'handle abort correctly
Dim pending As Integer = threadcount
Dim tempcount As Integer = 0
Dim oldcount As Integer = UCount
While pending > 0
pending = threadcount
tempcount = 0
For i = 0 To threadcount - 1
If threads(i).UpdateState = 0 Then
SecUpd(i) = ""
pending -= 1
tempcount += threads(i).UpdateCount
End If
Next
Interlocked.Exchange(UDone, Me.Stocks.Count - pending) 'Threadsafe method for assigning a value
Interlocked.Exchange(UCount, oldcount + tempcount) 'Threadsafe method for assigning a value
End While
End Try
End Sub

This is fantastically simplified, but threads by their nature will run at the same time (if possible and depending to some extent on the whim of the OS). If you want less going on simultaneously, use fewer threads. In your case, since you want the jobs done sequentially, you really only want one thread.
The best approach, as mentioned, is to create a background worker that runs on a single background thread. There's usually a queue to which you submit jobs in a thread-safe way from the foreground thread. The thread proc typically runs in an infinite loop, processing each job in the queue, and going to sleep waiting for new jobs when there are none.

Related

Progress Reporting causes BackGroundWorker to Run Slow. VB

I am using a BackgroundWorker to write to pixels on an internal bitmap, using a loop.
The BackgroundWorker DoWork routine does not access any GUI components.
If I run the loop without any Progress Reporting, the loop takes about 2 seconds to complete, which is satisfactory.
If I add Progress Reporting, the loop takes about 20 seconds to complete!! Not good!!
I notice that when Progress Reporting is on and the loop is running, the form cannot be dragged about the screen, and my Cancel button (code for this not included here) is not responded to until the loop completes.
Its as if the program was not running in a BackGroundWorker.
The Progress Reporting code is quite standard, and has been used a number of times before:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
worker.ReportProgress(CInt(100 * (i / (x * y)))
i += 1
Next
Next
Private Sub BGW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BGW.ProgressChanged
ProgressBar.Value = e.ProgressPercentage
StatusLabel.Text = "Progress: " & e.ProgressPercentage & "%"
End Sub
This all seems good and standard, until I realised that the ReportProgress line is actually sending its value to the ProgressChanged routine 12,500,000 times, when actually we only need to send a value 100 times. It was the flood of values that caused the problem.
This code works perfectly. I hope it is useful to someone else:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
Dim j As Double = (x * y) / 100
Dim k As Integer = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
i += 1
If i > j Then
k += 1
worker.ReportProgress(CInt(k))
i = 0
End If
Next
Next
You should use a public variable (Like "ReportValue") and a timer .
The timer is in a continuos loop and it set the value of the progressBar using the "ReportValue" .
On the other side , your backgroundWorker reports the progress in the "ReportValue" variable .
So you can refresh your ProgressBar without losing time in handling the [Progress state change]
then add this code to the timer:
If Not ReportValue = MyProgressBar.Value Then
MyProgressBar.Value = ReportValue
end if
The timer will refresh the progressbar value only if the value is changed
( preventing an high CPU usage )
Hope it helps :)
An easy way is to only report progress if there is progress to report:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
Dim oldProgress = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
Dim progress = CInt(100 * (i / (x * y))
If progress > oldProgress Then
worker.ReportProgress(progress)
oldProgress = progress
End If
i += 1
Next
Next

vb.net multithreading with multiple threads in a For..Next Loop

Hi folks I have the code below which i wanted to use all my processors cores. Originally, the code in the sub chekFileDupe was all within the For..Next loop in SearchForDupes sub and worked just fine on one thread. I'm a bit stuck as to create 4 threads that execute the checkFileDupe code so that i can check 4 items at a time, then wait till all 4 threads have completed. Then carry on with the next iteration of the loop.
This is the original code
Private Sub SearchForDupes()
Me.Refresh()
Dim totalrecords As Integer = dvSortedSearchResults.Count
Label1.Text = "Searching for duplicates"
Label1.Refresh()
dvSortedSearchResults.Sort = DataSortOrder
For i = 0 To totalrecords - 6 Step 4
Dim TrackDifference As Integer
Dim originalTrack, originalArtist, trackToCompare, artistToCompare As String
If i / 10 = CInt(i / 10) Then
Label2.Text = i.ToString + " of " + totalrecords.ToString
Label2.Refresh()
End If
originalArtist = mp3record(i, "Artist")
originalTrack = mp3record(i, "Track")
Dim ii As Integer = i + 1
While ii < totalrecords - 2
artistToCompare = mp3record(ii, "Artist")
trackToCompare = mp3record(ii, "Track")
TrackDifference = Difference(originalTrack, trackToCompare)
dvSortedSearchResults(ii).Item("Difference") = TrackDifference
'dgvSearchResults.Rows(ii).Cells("Difference").Value = trackdiff
If Difference(originalArtist, artistToCompare) < 6 Then
TrackDifference = Difference(originalTrack, trackToCompare)
If TrackDifference < 4 Then
dvSortedSearchResults(i).Item("Difference") = 999
dvSortedSearchResults(ii).Item("Difference") = TrackDifference
dvSortedSearchResults(ii).Item("chkdupe") = True
End If
Else
Exit While
End If
ii = ii + 1
End While
Next
Label2.Text = ""
Label1.Text = ""
End Sub
This is the first attempt at multithreading - probably naive but hey - everyone's new at something
Private Sub SearchForDupes()
'Dim query = (From record In dvSortedSearchResults Where record.Artist = "Abba" Select record).ToList
Me.Refresh()
Dim totalrecords As Integer = dvSortedSearchResults.Count
Label1.Text = "Searching for duplicates"
Label1.Refresh()
dvSortedSearchResults.Sort = DataSortOrder
Dim params(2) As Integer
For i = 0 To totalrecords - 6 Step 4
params(2) = totalrecords
params(1) = i
thread1 = New System.Threading.Thread(Sub() checkFileDupe(params))
thread1.Start()
params(1) = i + 1
thread2 = New System.Threading.Thread(Sub() checkFileDupe(params))
thread2.Start()
params(1) = i + 2
thread3 = New System.Threading.Thread(Sub() checkFileDupe(params))
thread3.Start()
params(1) = i + 3
thread4 = New System.Threading.Thread(Sub() checkFileDupe(params))
Next
Label2.Text = ""
Label1.Text = ""
End Sub
Private Sub checkFileDupe(params As Array)
Dim i As Integer = params(1)
Dim totalrecords As Integer = params(2)
Dim TrackDifference As Integer
Dim originalTrack, originalArtist, trackToCompare, artistToCompare As String
If i / 10 = CInt(i / 10) Then
Label2.Text = i.ToString + " of " + totalrecords.ToString
Label2.Refresh()
End If
originalArtist = mp3record(i, "Artist")
originalTrack = mp3record(i, "Track")
Dim ii As Integer = i + 1
While ii < totalrecords - 2
artistToCompare = mp3record(ii, "Artist")
trackToCompare = mp3record(ii, "Track")
TrackDifference = Difference(originalTrack, trackToCompare)
dvSortedSearchResults(ii).Item("Difference") = TrackDifference
'dgvSearchResults.Rows(ii).Cells("Difference").Value = trackdiff
If Difference(originalArtist, artistToCompare) < 6 Then
TrackDifference = Difference(originalTrack, trackToCompare)
If TrackDifference < 4 Then
dvSortedSearchResults(i).Item("Difference") = 999
dvSortedSearchResults(ii).Item("Difference") = TrackDifference
dvSortedSearchResults(ii).Item("chkdupe") = True
End If
ii = ii + 1
End While
End Sub Else
Exit While
End If
Actually, what I might advise you to do is forget about the code you have now and use a BackgroundWorker control. Start with just creating one thread to do the work and get that up and running. The advantage is that the background worker allows you to report progress back to the main UI thread. There should be plenty of tutorials out there.
I can try to tackle/indicate some of the problems in your current code, but to be honest there is a lot wrong with it.
You have a problem where you use the same underlying object, params(2), for each thread you create, so when you modify params you thereby modify the value that all the threads see. What you need to do is create a new array for each time you want to pass an argument to a new thread.
It's also extra confusing because you are using closures Sub () checkFileDupe(params), rather than using a correct signature for checkFileDupe and using Thread.Start to pass the argument.
I'd advise you to create a Structure to hold the arguments to your thread:
Private Structure FileDupeArguments
Public StartIndex As Integer
Public TotalRecords As Integer
End Structure
Then you can create a new thread via:
Dim params As FileDupeArguments
...
thread1 = New System.Threading.Thread(AddressOf checkFileDupe)
params = New FileDupeArguments With {.StartIndex = i, .TotalRecords = totalrecords}
thread1.Start(params)
And then declaring checkFileDupe as:
Sub checkFileDupe(argObj as Object)
Dim args As FileDupeArguments = CType(argObj, FileDupeArguments)
Dim i As Integer = args.StartIndex
Dim totalRecords As Integer = args.TotalRecords
...
End Sub
The important part here is that you send a new copy of FileDupeArguments to each thread. Also, no closures are needed.
There is an issue with you accessing controls from the threads you created.
For instance,
Label2.Text = i.ToString + " of " + totalrecords.ToString
Label2.Refresh()
will not work on a background thread and will give you errors. I'd advise you to not do direct progress reports from your worker threads. Like I mentioned, a BackgroundWorker will allow you to report back progress using events.
All the code that accesses dvSortedSearchResults suffers from the same or similar problems. If you access something from multiple threads, you need to apply locks. This is already more advanced and beyond the scope of this answer to explain.

What else can cause an AxWindowsMediaPlayer to play?

I have a button in my program that grabs a bunch of information from a DataGridView object (volume, url, delay, etc) and using that, it plays a file. I'm trying to get the delay to work (wait x number of seconds before playing) and I'm pretty it will work, but whenever I press the button, the play starts immediately. There is no Ctlcontrols.play() anywhere in the program except after the delay, so I have no idea what is causing it to play.
I explained my problem a little bit more in comments. Sorry if I didn't explain my code very well. If you could just tell my what else could be causing my player to start immediately, that would probably be enough.
'snd_btn_go is the button that is supposed to start it.
'This sub doesn't matter as much for the problem, it will just go to SndCueGO() if both numbers are in the valid range.
Private Sub snd_btn_go_Click(sender As Object, e As EventArgs) Handles snd_btn_go.Click
Dim cue1 As Integer
Dim cue2 As Integer
cue1 = If(Integer.TryParse(snd_txt_cue_1.Text, cue1), Int(snd_txt_cue_1.Text), snd_num1)
If snd_txt_cue_2.Text <> "" Then
cue2 = If(Integer.TryParse(snd_txt_cue_2.Text, cue2), Int(snd_txt_cue_2.Text), snd_num2)
Else
cue2 = -1
End If
If (cue1 <= dgSound.Rows.Count - 1 And cue1 > 0) Then
SndCueGO(cue1, cue2)
End If
End Sub
'This sub pulls all the info from the correct row in the DataGrid and assigns it to a list. It'll check if the start volume and end volume are the same and if they're not, it'll fade to the end volume.
Private Sub SndCueGO(cue1, cue2)
Dim cues() = {cue1, cue2}
snd_num1 = cue1
Dim cuedata1 = snd_ds.Tables(0).Rows(cue1 - 1)
Dim cuedata2 = snd_ds.Tables(0).Rows(cue1 - 1)
If cue2 <> -1 Then
snd_num2 = cue2
cuedata2 = snd_ds.Tables(0).Rows(cue2 - 1)
End If
Dim data() = {cuedata1, cuedata2}
For i = 0 To 1
If cues(i) <> -1 Then
snd_delay(i) = data(i).Item("Delay")
snd_startvol(i) = safeNum(data(i).Item("Start_Vol."))
snd_file(i) = data(i).Item("File")
snd_in(i) = data(i).Item("Fade_In")
snd_out(i) = data(i).Item("Fade_Out")
snd_vol(i) = safeNum(data(i).Item("Vol."))
snd_hold(i) = data(i).Item("Hold")
snd_af(i) = If(data(i).Item("AF") = "", False, True)
player_list(i).URL = snd_file(i)
snd_current(i) = snd_startvol(i)
If snd_startvol(i) <> snd_vol(i) Then 'snd_startvol(i) and snd_vol(i) were the same in all my tests, so this should not run.
snd_next(i) = snd_vol(i)
Dim num_steps_up = snd_in(i) * snd_speed
Dim num_steps_down = snd_out(i) * snd_speed
Dim diff = snd_vol(i) - snd_startvol(i)
Dim small_step As Single
If diff > 0 Then
small_step = diff / num_steps_up
ElseIf diff < 0 Then
small_step = diff / num_steps_down
End If
snd_steps(i) = small_step
timer_snd_fade.Tag = 0
timer_snd_fade.Enabled = True
End If
timer_snd_master.Tag = 0 'resets the tag to 0
timer_snd_master.Enabled = True 'Starts timer
End If
Next
End Sub
Private Sub timer_snd_master_Tick(sender As Object, e As EventArgs) Handles timer_snd_master.Tick
If sender.Tag = snd_delay(0) Then
Player1.Ctlcontrols.play() 'This is the only play command in the program
Debug.Print("tag " & sender.Tag) 'These print after the delay
Debug.Print("delay " & snd_delay(0))
End If
sender.Tag += 1
End Sub
Inspect the:
AxWindowsMediaPlayer player1 = ...; // get the player from UI
IWMPSettings sett = player.settings;
sett.autoStart == ??
see the docs.
Probably it is set to true, as it's default value. Simply set it to false it the player will not play until Ctlcontrols.play() is invoked.

Slow Processing

Well, I'm trying to convert various data "bytes" to "long".
And it seems to be very slow ...
Code:
For X = 0 To Map.MaxX
For Y = 0 To Map.MaxY
Map.Tile(X, Y).Data1 = Buffer.ReadLong
Map.Tile(X, Y).Data2 = Buffer.ReadLong
Map.Tile(X, Y).Data3 = Buffer.ReadLong
Map.Tile(X, Y).DirBlock = Buffer.ReadLong
ReDim Map.Tile(X, Y).Layer(0 To MapLayer.Layer_Count - 1)
For i = 0 To MapLayer.Layer_Count - 1
Map.Tile(X, Y).Layer(i).tileset = Buffer.ReadLong
Map.Tile(X, Y).Layer(i).X = Buffer.ReadLong
Map.Tile(X, Y).Layer(i).Y = Buffer.ReadLong
Next
Map.Tile(X, Y).Type = Buffer.ReadLong
Next
Next
Converter:
Public Function ReadLong(Optional ByVal peek As Boolean = True) As Long
If Buff.Count > readpos Then 'check to see if this passes the byte count
Dim ret As Long = BitConverter.ToInt64(Buff.ToArray, readpos)
If peek And Buff.Count > readpos Then
readpos += 8
End If
Return ret
Else
Throw New Exception("Byte Buffer Past Limit!") 'past byte count throw a new exception
End If
End Function
Anyone have tips or a solution?
One problem I can see is that you are calling buff.ToArray each time you read a long value. The ToArray method will make a copy of the buffer each time. You should call ToArray before you start processing the map and use the array instance when calling the BitConverter.ToInt64 method.

My program is assigning a value to ALL objects in an array. What's happening and how do I prevent it ? (VB 2008)

I have exhausted all of my options and am very desperate for help since I cannot figure out where the bug in my code is, or if there is something I don't understand.
I'm trying to create a "methinks it is a weasel!" mimmick from Richard Dawkins' late 80s documentary about evolution. The goal is to progress through a genetic algorithm until the algorithm guesses the correct answer through mutation and fitness tournaments.
Now, here's the problem:
Private Function fitnessTourney(ByVal editGuess() As Guess, ByVal popIndex As Integer, ByVal tourneySize As Integer, ByVal popNum As Integer)
Dim randInt(tourneySize - 1) As Integer
Dim loopCount1 As Integer = 0
Dim fitnessWinner As New Guess
fitnessWinner.setFitness(-50)
...
And, this loop is where I am experiencing the critical error
...
For i = 0 To tourneySize - 1
Randomize()
randInt(i) = Int(Rnd() * popNum)
While editGuess(randInt(i)).Used = True
If loopCount1 > tourneySize Then
loopCount1 = 0
For i2 = 0 To popNum - 1
editGuess(i2).setUsed(False)
Next
i = -1
Continue For
End If
loopCount1 += 1
randInt(i) = Int(Rnd() * popNum)
End While
editGuess(randInt(i)).determineFitness(correctPhrase)
editGuess(randInt(i)).setUsed(True)
Next
For i = 0 To popNum - 1
editGuess(i).setUsed(False)
Next
What this loop is trying to do is pick out four random instances of the editGuess array of objects. This loop tries to prevent one from being used multiple times, as the population is competing to one of the 10 members (highest fitness of the 4 chosen candidates is supposed to win).
The critical error is that I mysteriously get an endless loop where any instances of editGuess(randInt(i)).Used will always evaluate to true. I have tried to fix this by resetting all instances to False if it loops too many times.
The stumper is that I'll have all instances evaluate to False in the debugger. Then, when I reach "editGuess(randInt(i)).setUsed(True)" (the exact same thing as "editGuess(randInt(i)).Used = True"), it sets this value for EVERY member of the array.
Is there anyone who can see what is happening? I am so close to completing this!
Here's the Guess class:
Public Class Guess
Dim Fitness As Integer
Dim strLength As Integer
Dim strArray(30) As String
Dim guessStr As String
Dim Used As Boolean
Public Sub New()
Fitness = 0
guessStr = ""
strLength = 0
Used = 0
End Sub
Public Sub determineFitness(ByVal correctPhrase As String)
Dim lowerVal
If guessStr.Length <= correctPhrase.Length Then
lowerVal = guessStr.Length
Else
lowerVal = correctPhrase.Length
End If
strArray = guessStr.Split("")
Fitness = 0 - Math.Abs(correctPhrase.Length - guessStr.Length)
For i = 0 To lowerVal - 1
If correctPhrase(i) = guessStr(i) Then
Fitness = Fitness + 1
End If
Next
End Sub
Public Sub Mutate(ByVal mutatepercentage As Decimal, ByVal goodLetters As String)
If mutatepercentage > 100 Then
mutatepercentage = 100
End If
If mutatepercentage < 0 Then
mutatepercentage = 0
End If
mutatepercentage = mutatepercentage / 100
If Rnd() < mutatepercentage Then
strLength = Int(Rnd() * 25) + 5
If strLength < guessStr.Length Then
guessStr = guessStr.Remove(strLength - 1)
End If
End If
For i = 0 To strLength - 1
If Rnd() < mutatepercentage Then
If i < guessStr.Length Then
guessStr = guessStr.Remove(i, 1).Insert(i, goodLetters(Int(Rnd() * goodLetters.Length)))
Else
guessStr = guessStr & goodLetters(Int(Rnd() * goodLetters.Length))
End If
End If
Next
End Sub
Public Sub setFitness(ByVal num As Integer)
Fitness = num
End Sub
Public Sub setStrLength(ByVal num As Integer)
strLength = num
End Sub
Public Sub initializeText()
End Sub
Public Sub setUsed(ByVal bVal As Boolean)
Used = bVal
End Sub
End Class
And, finally, here's where and how the function is called
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
population1(counter) = fitnessTourney(population1, counter, 4, 10)
population2(counter) = fitnessTourney(population2, counter, 4, 10)
population1(counter).Mutate(2, goodLetters)
population2(counter).Mutate(20, goodLetters)
Label1.Text = population1(counter).guessStr
Label2.Text = population2(counter).guessStr
counter += 1
If counter > 9 Then
counter = 0
End If
End Sub
End Class
EDIT 1:
Thank you guys for your comments.
Here is the custom constructor I use to the form. This is used to populate the population arrays that are passed to the fitnessTourney function with editGuess.
Public Sub New()
InitializeComponent()
Randomize()
For i = 0 To 9
population1(i) = New Guess
population2(i) = New Guess
Next
counter = 0
correctPhrase = "Methinks it is a weasel!"
goodLetters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !##$%^&*()_+-=?></.,;\|`'~"
goodLettersArr = goodLetters.Split("")
For i = 0 To 9
population1(i).setStrLength(Int(Rnd() * 25) + 5)
population2(i).setStrLength(Int(Rnd() * 25) + 5)
For i2 = 0 To population1(i).strLength
population1(i).guessStr = population1(i).guessStr & goodLetters(Int(Rnd() * goodLetters.Length))
Next
For i2 = 0 To population2(i).strLength
population2(i).guessStr = population2(i).guessStr & goodLetters(Int(Rnd() * goodLetters.Length))
Next
Label1.Text = population1(i).guessStr
Label2.Text = population2(i).guessStr
Next
population1(0).guessStr = correctPhrase
population1(0).determineFitness(correctPhrase)
End Sub
I haven't studied all of your code thoroughly, but one big problem is that you are calling Randomize from within the loop. Every time you call Randomize, it re-seeds the random numbers with the current time. Therefore, if you call it multiple times before the clock changes, you will keep getting the first "random" number in the sequence using that time which will always evaluate to the same number. When generating "random" numbers, you want to re-seed your random number generator as few times as possible. Preferably, you'd only seed it once when the application starts.
As a side note, you shouldn't be using the old VB6 style Randomize and Rnd methods. Those are only provided in VB.NET for backwards compatibility. You should instead be using the Random class. It's easier to use too. With the Random class, you don't even need to call a randomize-like method, since it automatically seeds itself at the point in time when you instantiate the object. So, in the case of the Random class, the thing to be careful is to make sure that you only instantiate the object once before entering any loop where you might be using it. If you create a new Random object inside a loop, it will similarly keep generating the same numbers.