Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a task's continuation?

My class has a method which produces a Task<int> object using a TaskCompletionSource<int>. Then it does some asynchronous operations and sets the result. I need to know whether I can trust the task's ContinueWith method or not:

public Task<int> CalculateAsync()
{
    var source = new TaskCompletionSource();
    DoSomeAsyncStuffAndSetResultOf(source);

    source.Task.ContinueWith(t => Console.WriteLine("Is this reliable?"));
    return source.Task;
}

Can the caller of CalculateAsync method do something with the produced task and prevent its continuation from running?

like image 318
Şafak Gür Avatar asked Oct 06 '22 15:10

Şafak Gür


1 Answers

You can pass a CancellationToken into various overloads of ContinueWith... that would be the most idiomatic way of just cancelling the continuation, IMO.

I don't think there's anything you can do to the parent task to cancel continuations. I kinda hope not, anyway...

EDIT: Okay, it sounds like you're trying not to let that happen. No, you don't need to worry. Unless the caller can somehow make the task run forever without ever completing, being cancelled or faulting, the continuation will run.

like image 171
Jon Skeet Avatar answered Oct 10 '22 02:10

Jon Skeet