在VB.Net中的UI线程和用户线程之间进行通信

时间:2016-06-09 05:51:25

标签: vb.net multithreading delegates ui-thread

首先,我创建了一个SampleClass,如下所示:

Public Class SampleClass
    Public a As String
    Public b As Integer
    Public Sub New(ByVal str1 As String, ByVal int1 As Integer)
        Me.a = str1
        Me.b = int1
    End Sub
    Public Sub TestSub()
        Me.a = Me.a & " done"
        Me.b += 3
    End Sub
End Class

然后我创建了一个名为MyForm的表单,其中有两个按钮名为Button1和Button2,另外三个文本框名为TextBox1,TextBox2和TextBox3。

Imports System.Threading
Public Class MyForm
    Dim MyArray() As Integer
    Dim I As Integer   
    Dim x As SampleClass, X1 As SampleClass
    Dim t() As Thread
    Dim ThreadIndex As Integer
    Private Sub MyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ThreadIndex = -1
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            x = New SampleClass("First Part", 1)
            X1 = New SampleClass("Next Part", 2)
            ThreadIndex = ThreadIndex + 1
            t(ThreadIndex) = New Thread(AddressOf UpdateText)
            t.Start(x)
            If TextBox1.InvokeRequired Then
                Me.TextBox1.Invoke(New MyDel(AddressOf UpdateText), x)
            Else                
                Me.TextBox1.Text = x.a 
                Me.TextBox2.Text = x.b
            End If
            ThreadIndex = ThreadIndex + 1
            t(ThreadIndex) = New Thread(AddressOf UpdateText)
            t1.Start(X1)
            If TextBox3.InvokeRequired Then
                Me.TextBox3.Invoke(New MyDel(AddressOf UpdateText), X1)
            Else
                Me.TextBox3.Text = X1.a 
            End If
        Catch ex As ThreadStartException

        End Try
    End Sub   
    Private Sub UpdateText(Temp As Object)        
        Temp.TestSub()        
    End Sub
    Private Delegate Sub MyDel(Temp As Object)
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        StopThread()
    End Sub

    Private Sub StopThread()    
        Dim Counter as Integer, I as Integer
        Try
              Counter = 0
              For I = 0 to ThreadIndex
                  If t(I).IsAlive then
                     T(I).Abort()
                     Counter = Counter + 1
                  End If
              Next
        Catch Ex as ThreadAbortException
        Finally
              ThreadIndex = ThreadIndex - Counter
        End Try
    End Sub
 End Class

只要TestSub没有花时间完成,此代码就可以顺利运行。在我原来的情况下,它需要一些时间来完成,因为它有很多工作要做。我正面临着这个问题。

假设TestSub正在处理该线程并且需要花费1分钟来做某事,然后它推断出变量a和b的值。

当我使用参数调用委托时,UI不会等待线程生成a和b的值,而是在线程运行时更新文本框中a和b的初始值。

有什么方法可以让我的UI等到用户线程完成其工作并产生变量a和b的新值,同时UI也可供用户做其他工作,即等待用户线程,UI可以被用户访问其他作品吗?

另一个问题,当我点击Button2停止线程时,它正在生成MessageBox为“Thread is aborted”,我不想显示。有没有办法避免这种情况?

0 个答案:

没有答案