How to create a cancelled task
The most direct way I know to create a canceled task is to use a TaskCompletionSource
:
var tcs = new TaskCompletionSource<int>();
tcs.TrySetCanceled();
return tcs.Task;
If you haven't used it before, TaskCompletionSource
provides a "promise-style" task, which basically allows you to say, "Here, take this Task
now, and I'll provide the result (or report an error/cancellation) whenever I'm ready." It's useful when you want to schedule/coordinate work yourself, as opposed to simply relying on a TaskScheduler
.
Alternatively, if you rewrite your method using async/await
, you can force the cancellation exception to automatically propagate to the result 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));
}
The next version of .Net (v4.5.3) is adding a way to create a cancelled task leveraging that internal constructor. There are both a generic and non-generic versions:
var token = new CancellationToken(true);
Task task = Task.FromCanceled(token);
Task<int> genericTask = Task.FromCanceled<int>(token);
Keep in mind that the CancellationToken
being used must be canceled before calling FromCanceled