gpt4 book ai didi

c# - 这个异步任务方法有什么问题?

转载 作者:太空狗 更新时间:2023-10-29 23:17:00 24 4
gpt4 key购买 nike

这只是一个简单的异步任务,但我总是遇到奇怪的编译器错误。此代码来自使用 VS2010 创建的 ASP.NET 4 项目中的 Web API 服务。

Even ContinueWith (non-generic) returns Task implicitly but this error still exists.

代码:

public class TestController : ApiController
{
public Task<HttpResponseMessage> Test()
{
string url = "http://www.stackoverflow.com";
var client = new HttpClient();

return client.GetAsync(url).ContinueWith<HttpResponseMessage>((request) =>
{
// Error 361 'System.Threading.Tasks.Task' does not contain a definition
// for 'Result' and no extension method 'Result' accepting a first argument
// of type 'System.Threading.Tasks.Task' could be found
// (are you missing a using directive or an assembly reference?)
var response = request.Result;
response.EnsureSuccessStatusCode();

// Error 364 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>' to 'System.Net.Http.HttpResponseMessage'
return response.Content.ReadAsStringAsync().ContinueWith<HttpResponseMessage>((read) =>
{
return new HttpResponseMessage();
});
});
}
}

最佳答案

364 错误是完全正常的,因为您返回的是 Task<Task<HttpResponseMessage>>而不是 Task<HttpResponseMessage> .修复后,361 错误也会消失。

所以你可以 Unwrap 结果:

public Task<HttpResponseMessage> Test()
{
string url = "http://www.stackoverflow.com";
var client = new HttpClient();
return client.GetAsync(url).ContinueWith(request =>
{
var response = request.Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().ContinueWith(t =>
{
var result = new HttpResponseMessage();
response.CreateContent(t.Result);
return response;
});
}).Unwrap();
}

关于c# - 这个异步任务方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799771/

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