I have a Task which is always blocked and I have a CancellationToken passed into it which is used to cancel the task. However the Continuation task is never executed which is set to execute on Task's cancellation. The code is:
_tokenSrc = new CancellationTokenSource();
var cnlToken = _tokenSrc.Token;
Task.Run(() =>
// _stream.StartStream() blocks forever
_stream.StartStream(), cnlToken)
.ContinueWith(ant =>
{
_logger.Warn("Stream task cancellation requested, stopping the stream");
_stream.StopStream();
_stream = null;
_logger.Warn("Stream stopped and task cancelled");
}, TaskContinuationOptions.OnlyOnCanceled);
Later somewhere else in the code ...
_tokenSrc.Cancel();
The reason I had to use a Task for _stream.StartStream() is that this call blocks forever (an api on which I have no control, note that _stream refers to a thirdparty Api which streams data from a webservice) so I had to invoke it on another thread.
What is the best way to cancel the task?