0

我正在尝试创建一个通用函数来创建线程,然后我需要将一个子例程名称传递给该函数,但我只能传递一个函数名称(这是无用的)。

我怎么能做到这一点?

有一种方法可以在不将委托声明出函数的情况下做到这一点?...因为就像我说的那样,我将创建一个通用函数来简化事情。

这是我的代码:

Public Class Form1

' Desired usage:
' Make_Thread(Thread Variable, Thread Name, Thread Priority, Thread Sub)
'
' Example:
' Make_Thread(Thread_1, "Low thread", Threading.ThreadPriority.Low, AddressOf Test_Sub)

Private Thread_1 As Threading.Thread ' Thread Variable

Private Function Make_Thread(Of TKey)(ByRef Thread_Variable As Threading.Thread, _
                       ByVal Thread_Name As String, _
                       ByVal Thread_Priority As Threading.ThreadPriority, _
                       ByRef Thread_Sub As Func(Of String, TKey)) As Boolean ' I'd ByRef a function but really I will pass a Subroutine.

    ' See if the thread is already running.
    Dim is_running As Boolean
    If Thread_Variable Is Nothing Then _
         is_running = False _
    Else is_running = Thread_Variable.IsAlive

    ' If the thread is already running, do nothing.
    If is_running Then Return False : Exit Function

    ' Make the thread.
    Thread_Variable = New Threading.Thread(AddressOf Thread_Sub)
    Thread_Variable.Priority = Thread_Priority
    Thread_Variable.IsBackground = True
    Thread_Variable.Name = Thread_Name

    ' Start the thread.
    Thread_Variable.Start()
    Return True

End Function

Private Sub Test_Sub()
    MsgBox("A message from the thread!")
End Sub

End Class
4

0 回答 0