question

melonNG-6986 avatar image
0 Votes"
melonNG-6986 asked llaxmikant answered

A task was canceled with IHttpClientFactory

I made a post method with IHttpClientFactory with .net 6 like this:

 public object Post(string URL,object PostObject,  Type ResponseObjectType)
         {
             try
             {
                 var client = clientFactory.CreateClient();                
                 client.Timeout = TimeSpan.FromSeconds(3);
                 var options = new JsonSerializerOptions();
                 options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);
                 string JsonContent = JsonSerializer.Serialize(PostObject, PostObject.GetType(), options);                
                 var response = client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;
                 if (response.StatusCode == System.Net.HttpStatusCode.NotFound || response.Content == null)
                 {
                     client.Dispose();
                     return null;
                 }
                 else
                 {
                     object Result;
                     if (ResponseObjectType == typeof(string))
                     {
                         Result = response.Content.ReadAsStringAsync().Result;
                     }
                     else
                     {
                         Result = response.Content.ReadFromJsonAsync(ResponseObjectType, options).Result;
                     }
                     client.Dispose();
                     return Result;
                 }
             }
             catch (Exception ex)
             {
                 LogException(ex, URL);
                 return null;
             }
         }

Sometimes (not always) the code runs with the error above:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Threading.Tasks.Task.GetExceptions(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at SIComponent.Global.Post(String URL, Object PostObject, Type ResponseObjectType) in C:\Project\Sample\SIComponent\Global.cs:line 317
at SIComponent.Middleware.BlackListMiddleware.Invoke(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\BlackListMiddleware.cs:line 135
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at SIComponent.Middleware.BlackListMiddleware.Invoke(HttpContext context)
at SIComponent.Middleware.RedirectUpperURLMiddleware.InvokeAsync(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\RedirectUpperURLMiddleware.cs:line 31
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at SIComponent.Middleware.RedirectUpperURLMiddleware.InvokeAsync(HttpContext context)
at SIComponent.Middleware.ExceptionMiddleware.Invoke(HttpContext context) in C:\Project\Sample\SIComponent\Middleware\ExceptionMiddleware.cs:line 25
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at SIComponent.Middleware.ExceptionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.TryServeStaticFile(HttpContext context, String contentType, PathString subPath)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.UseWhenExtensions.<>c_DisplayClass0_1.<UseWhen>b1(HttpContext context)
at Microsoft.AspNetCore.Rewrite.RewriteMiddleware.Invoke(HttpContext context)
at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.HandleResponse(HttpContext httpContext)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.HandleResponse(HttpContext httpContext)
at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.Invoke(HttpContext httpContext, IValidatorValueInvalidator validatorValueInvalidator)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Marvin.Cache.Headers.HttpCacheHeadersMiddleware.Invoke(HttpContext httpContext, IValidatorValueInvalidator validatorValueInvalidator)
at lambda_method1(Closure , Object , HttpContext , IServiceProvider )
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c
DisplayClass5_1.<UseMiddleware>b2(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context, ICorsPolicyProvider corsPolicyProvider)
at lambda_method2(Closure , Object , HttpContext , IServiceProvider )
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c
DisplayClass5_1.<UseMiddleware>b_2(HttpContext context)
at Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Hosting.HostingApplication.ProcessRequestAsync(Context context)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.HandleRequest()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.HandleRequest()
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()
--- End of stack trace from previous location ---

In addition, every time it throws error when posting the same URL at the code:
var response = client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;

What's wrong with this? Is it the problem with the remote server or my code? Thank you.


dotnet-aspnet-core-general
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @melonNG-6986

              var client = clientFactory.CreateClient();                
              client.Timeout = TimeSpan.FromSeconds(3);

In the Try-Catch statement, try to catch the TaskCanceledException and check the timeout, code like this:

 } catch (TaskCanceledException) {
     //Could have been caused by cancellation or timeout if you used one.
     //If that was the case, rethrow.
     //cancellationToken.ThrowIfCancellationRequested();
    
     //HttpClient throws TaskCanceledException when the request times out. That's dumb.
     //Throw TimeoutException instead and say how long we waited.
     string time;
     if (_httpClient.Timeout.TotalHours > 1) {
         time = $"{_httpClient.Timeout.TotalHours:N1} hours";
     } else if (_httpClient.Timeout.TotalMinutes > 1) {
         time = $"{_httpClient.Timeout.TotalMinutes:N1} minutes";
     } else if (_httpClient.Timeout.TotalSeconds > 1) {
         time = $"{_httpClient.Timeout.TotalSeconds:N1} seconds";
     } else {
         time = $"{_httpClient.Timeout.TotalMilliseconds:N0} milliseconds";
     }
     throw new TimeoutException($"No response after waiting {time}.");
 }

If the issue relates to the timeout, try to increase the timeout, such as this: a 10-second timeout is applied

              var client = clientFactory.CreateClient();                
              client.Timeout = TimeSpan.FromSeconds(10);
0 Votes 0 ·

Thank you very much.

0 Votes 0 ·

1 Answer

llaxmikant avatar image
0 Votes"
llaxmikant answered

you need to use async and await, change the following code and try

 public async object Post(string URL,object PostObject,  Type ResponseObjectType)
  {
                           
         \\ other code
              
          var response = await client.PostAsync(URL, new StringContent(JsonContent, Encoding.UTF8, "application/json")).Result;
             
 //other code
    
  }             


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.