HttpClient-작업이 취소 되었습니까?
하나 또는 두 개의 작업이있는 경우에는 제대로 작동하지만 둘 이상의 작업이 있으면 "작업이 취소되었습니다"라는 오류가 발생합니다.
List<Task> allTasks = new List<Task>();
allTasks.Add(....);
allTasks.Add(....);
Task.WaitAll(allTasks.ToArray(), configuration.CancellationToken);
private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token)
{
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(Constants.TimeOut);
if (data != null)
{
byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data));
MemoryStream memoryStream = new MemoryStream(byteArray);
httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType);
}
return httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
return response.Content.ReadAsStringAsync().ContinueWith(stringTask =>
{
var json = stringTask.Result;
return Helper.FromJSON<T>(json);
});
}).Unwrap();
}
가 TaskCanceledException
발생 하는 데는 두 가지 이유 가 있습니다.
- 라는 뭔가
Cancel()
온CancellationTokenSource
작업이 완료되기 전에 토큰 취소와 관련. - 요청 시간이 초과되었습니다. 즉에 지정한 기간 내에 완료되지 않았습니다
HttpClient.Timeout
.
내 생각에 그것은 타임 아웃이었다. (명시 적으로 취소 된 경우에는이를 파악했을 것입니다.) 예외를 검사하여보다 확실하게 확인할 수 있습니다.
try
{
var response = task.Result;
}
catch (TaskCanceledException ex)
{
// Check ex.CancellationToken.IsCancellationRequested here.
// If false, it's pretty safe to assume it was a timeout.
}
내 Main()
메서드가 반환하기 전에 작업이 완료되기를 기다리지 않았기 때문에이 문제가 발생 하여 Task<HttpResponseMessage> myTask
콘솔 프로그램이 종료되면 취소되었습니다.
The solution was to call myTask.GetAwaiter().GetResult()
in Main()
(from this answer).
Another possibility is that the result is not awaited on the client side. This can happen if any one method on the call stack does not use the await keyword to wait for the call to be completed.
Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.
참고URL : https://stackoverflow.com/questions/29179848/httpclient-a-task-was-cancelled
'Programming' 카테고리의 다른 글
기술적으로 Erlang의 프로세스가 OS 스레드보다 효율적인 이유는 무엇입니까? (0) | 2020.05.29 |
---|---|
안드로이드 웹뷰 느림 (0) | 2020.05.29 |
Websockets 클라이언트 API의 HTTP 헤더 (0) | 2020.05.29 |
파이썬 사전은 해시 테이블의 예입니까? (0) | 2020.05.29 |
Visual Studio 2010을 통한 .NET Framework 4.5 대상 지정 (0) | 2020.05.29 |