What is the difference concerning the functionality and meaning of the
TaskCompletionSource + SetResult vs Task + FromResult
in the SendAsync method?
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden) {ReasonPhrase = "HTTPS Required"};
var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(response);
return taskCompletionSource.Task;
}
return base.SendAsync(request, cancellationToken);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.RequestUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.BadRequest, "HTTPS is required for security reason.");
return Task.FromResult(reply);
}
return base.SendAsync(request, cancellationToken);
}
Task.FromResult was a new addition in .NET 4.5. It is a helper method that creates a TaskCompletionSource and calls SetResult. If you are using .NET 4 or earlier you will have to use SetResult.