Search code examples
c#cancellationtokensourcetaskcompletionsource

Why is the task from TaskCompletionSource not completed after 5 seconds?


When I set the CancellationTokenSource to cancel after 5 seconds. The TaskCompletionSource will not be cancelled.

[Test]
public async Task Test()
{
  var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));      
  var completionSource = new TaskCompletionSource(cts.Token);

  await completionSource.Task;
}

Solution

  • The TaskCompletionSource object doesn't take cancellation tokens in the constructor, it takes any object. It's not supposed to listen to cancellation tokens.

    You can read the MSDN article to see what the constructor does and how to use the TaskCompletionSource object.

    You probably want to use the SetCanceled method.