5
이것은 단순한 비동기 작업이지만 이상한 컴파일러 오류가 발생했습니다. 이 코드는 VS2010으로 작성된 ASP.NET 4 프로젝트의 웹 API 서비스에서 가져온 것입니다.이 비동기 작업 메서드의 문제점은 무엇입니까?
심지어 ContinueWith (일반이 아님)는 작업을 암시 적으로 반환하지만이 오류는 여전히 존재합니다.
코드 : 대신 Task<HttpResponseMessage>
의 Task<Task<HttpResponseMessage>>
를 반환하기 때문에
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();
});
});
}
}
덕분에, 나는 몹시 반환 값은 각 ContinueWidth에 대한 작업 <>에 싸여 것을 잊어 버렸습니다. 코드는 이제 컴파일하지만 난 예상대로 여전히 작동하지 확신 : 스레드는 client.GetAsync 및 response.Content.ReadAsStringAsync 호출을 실행하는 동안 잠시 동안 무료입니다? –
@Tiendq, 나는 'Unwrap'을 사용하여 더 나은 예제로 나의 대답을 업데이트했다. 이렇게하면 HTTP 요청을 실행하는 동안 작업 스레드가 비어있게됩니다. –