gpt4 book ai didi

c# - 任务 FromResult 与 TaskCompletionSource SetResult

转载 作者:IT王子 更新时间:2023-10-29 04:46:52 24 4
gpt4 key购买 nike

关于的功能和含义有什么区别

TaskCompletionSource + SetResult vs Task + FromResult

在 SendAsync 方法中?

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 是 .NET 4.5 中的新增功能。它是创建 TaskCompletionSource 并调用 SetResult 的辅助方法。如果您使用的是 .NET 4 或更早版本,则必须使用 SetResult。

关于c# - 任务 FromResult 与 TaskCompletionSource SetResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21256110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com