astrowalker astrowalker - 1 year ago 133
C# Question

How to combine TaskCompletionSource and CancellationTokenSource?

I have such code (simplified here) which awaits finishing task:

var task_completion_source = new TaskCompletionSource<bool>();
observable.Subscribe(b =>
if (b)
await task_completion_source.Task;

The idea is to subscribe and wait for the
in the stream of booleans. This finishes the "task" and I can move on beyond the

However I would like to cancel -- but not subscription, but awaiting. I would like to pass cancel token (somehow) to
so when I cancel the token source, the
will move on.

How to do it?

is external to this code, all I have here is the token from it.

Evk Evk
Answer Source

If I understand you correctly, you can do it like this:

CancellationToken ct;
ct.Register(() =>
     // this callback will be executed when token is cancelled

Note that it will throw an exception on your await, which you have to handle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download