AsyncExtensions.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #if CSHARP_7_OR_LATER
  2. using System;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace BestHTTP
  6. {
  7. public static class AsyncExtensions
  8. {
  9. public static Task<T> GetFromJsonResultAsync<T>(this HTTPRequest request, CancellationToken token = default)
  10. {
  11. return HTTPRequestAsyncExtensions.CreateTask<T>(request, token, (req, resp, tcs) =>
  12. {
  13. switch (req.State)
  14. {
  15. // The request finished without any problem.
  16. case HTTPRequestStates.Finished:
  17. if (resp.IsSuccess)
  18. tcs.TrySetResult(BestHTTP.JSON.LitJson.JsonMapper.ToObject<T>(resp.DataAsText));
  19. else
  20. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Request finished Successfully, but the server sent an error.", resp));
  21. break;
  22. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  23. case HTTPRequestStates.Error:
  24. HTTPRequestAsyncExtensions.VerboseLogging(request, "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
  25. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("No Exception", null, req.Exception));
  26. break;
  27. // The request aborted, initiated by the user.
  28. case HTTPRequestStates.Aborted:
  29. HTTPRequestAsyncExtensions.VerboseLogging(request, "Request Aborted!");
  30. tcs.TrySetCanceled();
  31. break;
  32. // Connecting to the server is timed out.
  33. case HTTPRequestStates.ConnectionTimedOut:
  34. HTTPRequestAsyncExtensions.VerboseLogging(request, "Connection Timed Out!");
  35. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Connection Timed Out!"));
  36. break;
  37. // The request didn't finished in the given time.
  38. case HTTPRequestStates.TimedOut:
  39. HTTPRequestAsyncExtensions.VerboseLogging(request, "Processing the request Timed Out!");
  40. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Processing the request Timed Out!"));
  41. break;
  42. }
  43. });
  44. }
  45. }
  46. }
  47. #endif