无法在vb.net中启动线程

时间:2012-02-05 16:03:26

标签: vb.net winforms multithreading

我试图在一个函数的表单中启动一个线程,运行大约需要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

2 个答案:

答案 0 :(得分:3)

  

...当我通过调试器观看它时,它只是“结束”   子” ...

请注意thread1.Start()不会阻止当前线程。

CheckForIllegalCrossThreadCalls设置为False将不会执行任何操作,但是当您访问UI线程拥有的控件的属性时,忽略抛出的异常 - 这也是您的问题:

  • 您创建新主题
  • 新主题调用getSecurityStuff
  • 您尝试声明新的clsSecurityView,其中cmbTickerEntry.Text为参数。
  • EXCEPTION - 你在另一个线程上尝试访问UI线程拥有的控件!
  • 没有异常显示,因为您已将CheckForIllegalCrossThreadCalls设置为False

同样处理fillData ...尝试访问UI线程之外的控件。

解决方案:使用Invoke / BeginInvoke执行应该读取/修改UI线程所拥有的控件属性的代码。

答案 1 :(得分:-1)

试试这个

Dim action as New Action(AddressOf getSecurityStuff)
action.BeginInvoke(Nothing, Nothing)