WWWAsync.cs 2.1 KB

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