WWWAsync.cs 2.1 KB

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