The most direct way to create a canceled task is to use TaskCompletionSource :
var tcs = new TaskCompletionSource<int>(); tcs.TrySetCanceled(); return tcs.Task;
If you have not used it before, TaskCompletionSource provides a βpromiseβ task, which basically allows you to say: βHere, take this Task now and I will give the result (or report an error / cancellation) when I am ready.β This is useful when you want to plan / coordinate work yourself, and not just rely on TaskScheduler .
Alternatively, if you rewrite your method using async/await , you can force the cancellation exception to automatically propagate to the result of the Task :
public async override Task<int> ReadAsync( byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await _connection.ReceiveAsync( new ArraySegment<byte>( buffer, offset, count)); }
source share