Call to TaskFactory.StartNew() with parameters errors with "reference to non-shared member requires an object reference "

385 Views Asked by At

The code segment has the error "reference to non-shared member requires an object reference " in Line 7. I am using a MS example to work through this, so it should work. Thanks!

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
1

There are 1 best solutions below

0
Panagiotis Kanavos On

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