AsyncExtensions.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. {
  19. try
  20. {
  21. tcs.TrySetResult(BestHTTP.JSON.LitJson.JsonMapper.ToObject<T>(resp.DataAsText));
  22. }
  23. catch (Exception ex)
  24. {
  25. tcs.TrySetException(ex);
  26. }
  27. }
  28. else
  29. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Request finished Successfully, but the server sent an error.", resp));
  30. break;
  31. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  32. case HTTPRequestStates.Error:
  33. HTTPRequestAsyncExtensions.VerboseLogging(request, "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
  34. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("No Exception", null, req.Exception));
  35. break;
  36. // The request aborted, initiated by the user.
  37. case HTTPRequestStates.Aborted:
  38. HTTPRequestAsyncExtensions.VerboseLogging(request, "Request Aborted!");
  39. tcs.TrySetCanceled();
  40. break;
  41. // Connecting to the server is timed out.
  42. case HTTPRequestStates.ConnectionTimedOut:
  43. HTTPRequestAsyncExtensions.VerboseLogging(request, "Connection Timed Out!");
  44. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Connection Timed Out!"));
  45. break;
  46. // The request didn't finished in the given time.
  47. case HTTPRequestStates.TimedOut:
  48. HTTPRequestAsyncExtensions.VerboseLogging(request, "Processing the request Timed Out!");
  49. tcs.TrySetException(HTTPRequestAsyncExtensions.CreateException("Processing the request Timed Out!"));
  50. break;
  51. }
  52. });
  53. }
  54. }
  55. }
  56. #endif