Programming

HttpClient-작업이 취소 되었습니까?

procodes 2020. 5. 29. 23:35
반응형

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발생 하는 데는 두 가지 이유 가 있습니다.

  1. 라는 뭔가 Cancel()CancellationTokenSource작업이 완료되기 전에 토큰 취소와 관련.
  2. 요청 시간이 초과되었습니다. 즉에 지정한 기간 내에 완료되지 않았습니다 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

반응형