使用Action实例启动新线程

时间:2015-09-23 15:54:25

标签: .net vb.net multithreading

如何在VB.NET中使用操作对象启动新线程?

_taskopts.AddTask(1, AddressOf MyMethod, "Test Task", True)                  

...

Public Sub AddTask(minfreq As Double, subroutine As Action, name As String, immediate As Boolean)
    If minfreq > 0 Then
        Dim task As New TaskObj With {.minfreq = minfreq, .subroutine = subroutine, .name = name}

        If immediate Then
            task.lastrun = New Date(1970, 1, 1)
        Else
            task.lastrun = Now()
        End If

        _tasks.Add(task)
    End If
End Sub

Public Sub ExecuteTasks()
    For Each task As TaskObj In _tasks
        Try
            TaskOp(task)
        Catch ex As Exception
            InvokeMessage("TaskOpts Execute Error: " & ex.Message)
        End Try
    Next
End Sub

Private Sub TaskOp(ByRef task As TaskObj)
    If Now.Subtract(task.lastrun).TotalMinutes > task.minfreq Then
        task.lastrun = Now()

        Dim taskthread As New Thread(AddressOf task.subroutine) '*****ERROR HERE*****   
        taskthread.Start()

        Thread.Sleep(100)
    End If
End Sub

这会导致错误:“AddressOf操作数必须是方法的名称。”我想也许我需要使用除Action对象以外的东西,也许是通过AddTask子传递AddressOf的某种方式。

1 个答案:

答案 0 :(得分:0)

在TaskOp子中,您有compilcation错误传递一组任务或添加您必须在那里执行的任务。下面的示例显示如何将整数参数传递给函数。您可以根据需要传递其他参数。

 Dim tasks As New List(Of Task)()
        For i As Integer = 0 To 9
            Dim temp_i As Integer = i
            tasks.Add(Task.Run(Function() CallYourFunction(temp_i)))
        Next
        Await Task.WhenAll(tasks)