[VB.NET Tips]线程传递参数四种方法

Thread线程启动方法,一般来说要么是一个无参数的方法,要么是一个带有object参数的方法并且在Start时传递参数的值。
但是我们可以利用一些技巧给方法传递不受限制的参数。这些方法又可以在实际使用过程相互融合。
方法简单直接上代码,供君参考。

Imports System.Threading
Module Module1

    Sub Main()

        '第一种:在Start中传递参数值,但方法中的参数类型需为object类型
        Dim t1 As New Thread(AddressOf CountNumber)
        t1.Start(10)

        '第二种:通过Lambda表达式创建线程,可以传递任意的参数
        Dim t2 As New Thread(Sub()
                                 PrintNumber(20)
                             End Sub)
        t2.Start()

        '第三种:通过实例化类来传递参数,然后调用类方法
        Dim c As New Count(10)
        Dim t3 As New Thread(AddressOf c.CountNumber)
        t3.Start()

        '第四种:通过传递类或结构,以达到向方法传递多个参数
        Dim p As New Person() With {
            .FirstName = "严",
            .LastName = "查散"
            }
        Dim t4 As New Thread(AddressOf ShowName)
        t4.Start(p)

        Console.Read()

    End Sub

    '传递单个参数
    Private Sub CountNumber(number As Object)

        Dim sum As Integer

        For i As Integer = 1 To Integer.Parse(number)

            sum += i

        Next

        Console.WriteLine(sum)

    End Sub

    '传递非object参数
    Private Sub PrintNumber(number As Integer)

        Console.WriteLine(number)

    End Sub

    '把方法包装成类,在实例化时传递参数
    Class Count

        Dim number As Integer

        Sub New(number As Integer)

            Me.number = number

        End Sub

        Public Sub CountNumber()

            Dim sum As Integer

            For i As Integer = 1 To Integer.Parse(number)

                sum += i

            Next

            Console.WriteLine(sum)

        End Sub

    End Class

    '传递一个类或结构达到传递多个参数
    Private Sub ShowName(person As Object)

        Dim myPerson As Person = CType(person, Person)

        Console.WriteLine(myPerson.FirstName & myPerson.LastName)

    End Sub

    Class Person

        Public Property FirstName As String
        Public Property LastName As String

    End Class

End Module

posted @ 2020-11-10 14:32  朽木Sweayer  阅读(43)  评论(0编辑  收藏