How to cancel a Task in await?

后端 未结 4 1409
孤独总比滥情好
孤独总比滥情好 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:46

    Or, in order to avoid modifying slowFunc (say you don't have access to the source code for instance):

    var source = new CancellationTokenSource(); //original code
    source.Token.Register(CancelNotification); //original code
    source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
    var completionSource = new TaskCompletionSource(); //New code
    source.Token.Register(() => completionSource.TrySetCanceled()); //New code
    var task = Task.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code
    
    //original code: await task;  
    await Task.WhenAny(task, completionSource.Task); //New code
    
    
    

    You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:

    await Task.WhenAny(task, source.Token.AsTask());
    

    提交回复
    热议问题