How to combine TaskCompletionSource and CancellationTokenSource?

I have code like this (simplified here) that waits for the task to complete:

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

The idea is to subscribe and wait truein the boolean stream. This completes the "task", and I can move on await.

However, I would like to cancel, but not subscribe, but expect. I would like to pass the cancellation token (somehow) to task_completion_source, so when I cancel the token, it awaitwill move on.

How to do it?

Update : CancellationTokenSourceis external to this code, all I have is a token from it.

+4
2

, :

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

, , .

+9

. , . , , Register, , .

Task.WaitAsync AsyncEx.Tasks library:

var task_completion_source = new TaskCompletionSource<bool>();
observable.Subscribe(b => 
{ 
  if (b) 
    task_completion_source.SetResult(true); 
});
await task_completion_source.Task.WaitAsync(cancellationToken);

, ToTask, TaskCompletionSource. , ToTask .

+4

Source: https://habr.com/ru/post/1656939/


All Articles