WWWAsync.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using UnityEngine;
  5. namespace Model
  6. {
  7. [ObjectEvent]
  8. public class WWWAsyncEvent : ObjectEvent<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. this.tcs.SetResult(true);
  59. }
  60. public Task<bool> LoadFromCacheOrDownload(string url, Hash128 hash)
  61. {
  62. url = url.Replace(" ", "%20");
  63. this.www = WWW.LoadFromCacheOrDownload(url, hash, 0);
  64. this.tcs = new TaskCompletionSource<bool>();
  65. return this.tcs.Task;
  66. }
  67. public Task<bool> LoadFromCacheOrDownload(string url, Hash128 hash, CancellationToken cancellationToken)
  68. {
  69. url = url.Replace(" ", "%20");
  70. this.www = WWW.LoadFromCacheOrDownload(url, hash, 0);
  71. this.tcs = new TaskCompletionSource<bool>();
  72. cancellationToken.Register(() => { this.isCancel = true; });
  73. return this.tcs.Task;
  74. }
  75. public Task<bool> DownloadAsync(string url)
  76. {
  77. url = url.Replace(" ", "%20");
  78. this.www = new WWW(url);
  79. this.tcs = new TaskCompletionSource<bool>();
  80. return this.tcs.Task;
  81. }
  82. public Task<bool> DownloadAsync(string url, CancellationToken cancellationToken)
  83. {
  84. url = url.Replace(" ", "%20");
  85. this.www = new WWW(url);
  86. this.tcs = new TaskCompletionSource<bool>();
  87. cancellationToken.Register(() => { this.isCancel = true; });
  88. return this.tcs.Task;
  89. }
  90. public override void Dispose()
  91. {
  92. if (this.Id == 0)
  93. {
  94. return;
  95. }
  96. base.Dispose();
  97. www?.Dispose();
  98. this.www = null;
  99. }
  100. }
  101. }