WWWAsync.cs 2.1 KB

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