I am trying to start a thread in a form for a function that takes about 5 seconds to run so I can keep the UI from locking up. I have the following code below, but it fails when it hits “thread1.start.” When I watch it though a debugger it just goes strait to “End Sub” and it does not go to the getSecurityStuff() method that I am expecting it to go to. Any ideas?
Thanks!
Imports System.Threading
Public Class frmAddAssets
Private theDict As Dictionary(Of String, String) = Nothing
Private Sub frmAddAssets_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub cmbTickerEntry_Leave(sender As System.Object, e As System.EventArgs) Handles cmbTickerEntry.Leave
Dim thread1 As New Thread(New ThreadStart(AddressOf getSecurityStuff))
thread1.Start()
End Sub
Public Sub getSecurityStuff()
Dim getData As New clsSecurityView(cmbTickerEntry.Text())
Try
theDict = getData.getStockData()
Catch ex As Exception
Throw
End Try
filldata()
End Sub
Private Sub filldata()
Dim list As New List(Of String)(theDict.Keys)
txtTicker.Text = cmbTickerEntry.Text.ToString()
For Each kvp As KeyValuePair(Of String, String) In theDict
Select Case True
Case kvp.Key = "Name"
txtSecurityName.Text = kvp.Value.ToString()
Case kvp.Key = "Price"
txtPrice.Text = kvp.Value.ToString()
Case kvp.Key = "Market Capitalization"
txtMarketCap.Text = kvp.Value.ToString()
Case kvp.Key = "Dividend Yield"
txtDivYield.Text = kvp.Value.ToString()
Case kvp.Key = "PE Ratio"
txtPERatio.Text = kvp.Value.ToString()
Case kvp.Key = "EPS"
txtEPS.Text = kvp.Value.ToString()
End Select
Next
End Sub
End Class
Please note that
thread1.Start()won’t block the current thread.Setting
CheckForIllegalCrossThreadCallstoFalsewon’t do anything, but ignore the exception(s) that’s throwen, when you access the properties of a control owned by the UI thread – which also is your problem:getSecurityStuffclsSecurityView, withcmbTickerEntry.Textas parameter.CheckForIllegalCrossThreadCallstoFalseSame deal with
fillData… trying to access controls outside the UI thread.Solution: Use
Invoke/BeginInvoketo execute code that should read/modify properties on controls owned by the UI thread.