How to cancel a Task in await?

后端 未结 4 1395
孤独总比滥情好
孤独总比滥情好 2020-11-22 15:20

I\'m playing with these Windows 8 WinRT tasks, and I\'m trying to cancel a task using the method below, and it works to some point. The CancelNotification method DOES get ca

4条回答
  •  一向
    一向 (楼主)
    2020-11-22 15:39

    I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.

    Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);
    

    Where the event handler looks like this

    private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
    {
        if (status == AsyncStatus.Canceled)
        {
            return;
        }
        CommentsItemsControl.ItemsSource = Comments.Result;
        CommentScrollViewer.ScrollToVerticalOffset(0);
        CommentScrollViewer.Visibility = Visibility.Visible;
        CommentProgressRing.Visibility = Visibility.Collapsed;
    }
    

    With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.

提交回复
热议问题