我试图在一个函数的表单中启动一个线程,运行大约需要5秒钟,这样我就可以防止UI被锁定。我在下面有以下代码,但是当它命中“thread1.start”时它会失败。当我通过调试器观察它时,它只会进入“End Sub”并且它不会转到我期望它去的getSecurityStuff()方法。有什么想法吗?
谢谢!
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
答案 0 :(得分:3)
...当我通过调试器观看它时,它只是“结束” 子” ...
请注意thread1.Start()
不会阻止当前线程。
将CheckForIllegalCrossThreadCalls
设置为False
将不会执行任何操作,但是当您访问UI线程拥有的控件的属性时,忽略抛出的异常 - 这也是您的问题:
getSecurityStuff
clsSecurityView
,其中cmbTickerEntry.Text
为参数。CheckForIllegalCrossThreadCalls
设置为False
同样处理fillData
...尝试访问UI线程之外的控件。
解决方案:使用Invoke
/ BeginInvoke
执行应该读取/修改UI线程所拥有的控件属性的代码。
答案 1 :(得分:-1)
试试这个
Dim action as New Action(AddressOf getSecurityStuff)
action.BeginInvoke(Nothing, Nothing)