Async always WaitingForActivation

后端 未结 5 1108
夕颜
夕颜 2020-12-02 21:50

I am trying to figure out what the async & await keywords are all about, however the output isn\'t what I\'m expecting.

The console app

5条回答
  •  天涯浪人
    2020-12-02 22:49

    this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.

    '''  Reference to the awaiting task. 
    '''  The awaiting task. 
    Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task
    
    '''  Reference to the Action task; this task status undergoes changes. 
    Protected ReadOnly Property ActionTask As Threading.Tasks.Task
    
    '''  Reference to the cancellation source. 
    Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource
    
    '''  Starts the action task. 
    '''  The action to stream the entities, which calls
    '''                           . 
    '''  The awaiting task. 
    Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
        Me._ActionTask = Task.Run(taskAction)
        Await Me.ActionTask '  Task.Run(streamEntitiesAction)
        Try
            Me.ActionTask?.Wait()
            Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
        Catch ex As AggregateException
            Me.OnExceptionOccurred(ex)
        Finally
            Me.TaskCancellationSource.Dispose()
        End Try
    End Function
    
    '''  Starts Streaming the events. 
    '''  Thrown when the requested operation is invalid. 
    '''             The bucket key. 
    '''               The timeout. 
    '''  The action to stream the entities, which calls
    '''                                     . 
    Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
        If Me.IsTaskActive Then
            Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
        Else
            Me._TaskCancellationSource = New Threading.CancellationTokenSource
            Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
            Me.TaskCancellationSource.CancelAfter(timeout)
            ' the action class is created withing the Async/Await function
            Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
        End If
    End Sub
    

提交回复
热议问题