WWWAsync.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using UnityEngine;
  5. namespace Model
  6. {
  7. [ObjectSystem]
  8. public class WwwAsyncSystem : ObjectSystem<WWWAsync>, IUpdate
  9. {
  10. public void Update()
  11. {
  12. this.Get().Update();
  13. }
  14. }
  15. public class WWWAsync: Entity
  16. {
  17. public WWW www;
  18. public bool isCancel;
  19. public TaskCompletionSource<bool> tcs;
  20. public float Progress
  21. {
  22. get
  23. {
  24. if (this.www == null)
  25. {
  26. return 0;
  27. }
  28. return this.www.progress;
  29. }
  30. }
  31. public int ByteDownloaded
  32. {
  33. get
  34. {
  35. if (this.www == null)
  36. {
  37. return 0;
  38. }
  39. return this.www.bytesDownloaded;
  40. }
  41. }
  42. public void Update()
  43. {
  44. if (this.isCancel)
  45. {
  46. this.tcs.SetResult(false);
  47. return;
  48. }
  49. if (!this.www.isDone)
  50. {
  51. return;
  52. }
  53. if (!string.IsNullOrEmpty(this.www.error))
  54. {
  55. this.tcs.SetException(new Exception($"WWWAsync error: {this.www.error}"));
  56. return;
  57. }
  58. var t = this.tcs;
  59. this.tcs = null;
  60. t?.SetResult(true);
  61. }
  62. public Task<bool> LoadFromCacheOrDownload(string url, Hash128 hash)
  63. {
  64. url = url.Replace(" ", "%20");
  65. this.www = WWW.LoadFromCacheOrDownload(url, hash, 0);
  66. this.tcs = new TaskCompletionSource<bool>();
  67. return this.tcs.Task;
  68. }
  69. public Task<bool> LoadFromCacheOrDownload(string url, Hash128 hash, CancellationToken cancellationToken)
  70. {
  71. url = url.Replace(" ", "%20");
  72. this.www = WWW.LoadFromCacheOrDownload(url, hash, 0);
  73. this.tcs = new TaskCompletionSource<bool>();
  74. cancellationToken.Register(() => { this.isCancel = true; });
  75. return this.tcs.Task;
  76. }
  77. public Task<bool> DownloadAsync(string url)
  78. {
  79. url = url.Replace(" ", "%20");
  80. this.www = new WWW(url);
  81. this.tcs = new TaskCompletionSource<bool>();
  82. return this.tcs.Task;
  83. }
  84. public Task<bool> DownloadAsync(string url, CancellationToken cancellationToken)
  85. {
  86. url = url.Replace(" ", "%20");
  87. this.www = new WWW(url);
  88. this.tcs = new TaskCompletionSource<bool>();
  89. cancellationToken.Register(() => { this.isCancel = true; });
  90. return this.tcs.Task;
  91. }
  92. public override void Dispose()
  93. {
  94. if (this.IsDisposed)
  95. {
  96. return;
  97. }
  98. base.Dispose();
  99. www?.Dispose();
  100. this.www = null;
  101. this.tcs = null;
  102. }
  103. }
  104. }