【问题标题】:Start a new thread using an Action instance使用 Action 实例启动新线程
【发布时间】:2015-09-23 15:54:25
【问题描述】:

如何在 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 的某种方式。

【问题讨论】:

    标签: .net vb.net multithreading


    【解决方案1】:

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

     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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多