[英]Does Task.Run(Action) Start a new Thread id there are no more threads in the ThreadPool?
[英]Start a new thread using an Action instance
如何使用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的某種方式。
在出現編譯錯誤的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.