0

代码段在第 7 行有错误“对非共享成员的引用需要对象引用”。我正在使用 MS 示例来解决这个问题,所以它应该可以工作。谢谢!

Sub main()
    Dim TokenSource As New CancellationTokenSource()
    Dim token As CancellationToken = TokenSource.Token
    Dim TaskX As Task
    Dim tasks As New ConcurrentBag(Of Task)()
    MessageBox.Show("In Module taskStore running Main subroutine")
    TaskX = TaskFactory.StartNew(Sub() DoSomeWork(1, token), token)
    tasks.Add(t)
End Sub

Sub DoSomeWork(ByVal taskNum As Integer, ByVal ct As CancellationToken)
    If ct.IsCancellationRequested = True Then
        MessageBox.Show("TaskX cancelled before it got started")
        ct.ThrowIfCancellationRequested()
    End If
    Dim maxIterations As Integer = 100

End Sub
4

1 回答 1

0

The example you linked to uses :

t = Task.Factory.StartNew(Sub() DoSomeWork(1, token), token)

not

t = TaskFactory.StartNew(Sub() DoSomeWork(1, token), token)

The Task.Factory property returns a default TaskFactory instance that can be used to call the StartNew object method.

That method isn't used since 2012 when Async/Await and Task.Run were introduced. That's explained in the docs as well:

Starting with the .NET Framework 4.5, the Task.Run method provides the easiest way to create a Task object with default configuration values.

Right now the oldest supported .NET Framework version is 4.5.2 but even that will go out of support in April 2022, in just 3 months. Your code should target 4.6.2 at least, although 4.7.1 or 4.8 would be better

于 2022-01-12T15:05:26.093 回答