UnityWebRequestOperation.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using UnityEngine.Networking;
  5. using UnityEngine;
  6. namespace YooAsset
  7. {
  8. internal abstract class UnityWebRequestOperation : AsyncOperationBase
  9. {
  10. protected enum ESteps
  11. {
  12. None,
  13. CreateRequest,
  14. Download,
  15. Done,
  16. }
  17. protected UnityWebRequest _webRequest;
  18. protected readonly string _requestURL;
  19. protected ESteps _steps = ESteps.None;
  20. // 超时相关
  21. protected readonly float _timeout;
  22. protected ulong _latestDownloadBytes;
  23. protected float _latestDownloadRealtime;
  24. private bool _isAbort = false;
  25. public string URL
  26. {
  27. get { return _requestURL; }
  28. }
  29. internal UnityWebRequestOperation(string url, int timeout)
  30. {
  31. _requestURL = url;
  32. _timeout = timeout;
  33. }
  34. /// <summary>
  35. /// 释放下载器
  36. /// </summary>
  37. protected void DisposeRequest()
  38. {
  39. if (_webRequest != null)
  40. {
  41. _webRequest.Dispose();
  42. _webRequest = null;
  43. }
  44. }
  45. /// <summary>
  46. /// 检测超时
  47. /// </summary>
  48. protected void CheckRequestTimeout()
  49. {
  50. // 注意:在连续时间段内无新增下载数据及判定为超时
  51. if (_isAbort == false)
  52. {
  53. if ( _latestDownloadBytes != _webRequest.downloadedBytes)
  54. {
  55. _latestDownloadBytes = _webRequest.downloadedBytes;
  56. _latestDownloadRealtime = Time.realtimeSinceStartup;
  57. }
  58. float offset = Time.realtimeSinceStartup - _latestDownloadRealtime;
  59. if (offset > _timeout)
  60. {
  61. _webRequest.Abort();
  62. _isAbort = true;
  63. }
  64. }
  65. }
  66. /// <summary>
  67. /// 检测请求结果
  68. /// </summary>
  69. protected bool CheckRequestResult()
  70. {
  71. #if UNITY_2020_3_OR_NEWER
  72. if (_webRequest.result != UnityWebRequest.Result.Success)
  73. {
  74. Error = $"URL : {_requestURL} Error : {_webRequest.error}";
  75. return false;
  76. }
  77. else
  78. {
  79. return true;
  80. }
  81. #else
  82. if (_webRequest.isNetworkError || _webRequest.isHttpError)
  83. {
  84. Error = $"URL : {_requestURL} Error : {_webRequest.error}";
  85. return false;
  86. }
  87. else
  88. {
  89. return true;
  90. }
  91. #endif
  92. }
  93. }
  94. }