WebClientTestAsync.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. //
  2. // System.Net.WebClientTestAsync
  3. //
  4. // Authors:
  5. // Martin Baulig ([email protected])
  6. //
  7. // Copyright 2012 Xamarin Inc. (http://www.xamarin.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_4_5
  30. using System;
  31. using System.IO;
  32. using System.Collections.Generic;
  33. using System.Threading;
  34. using System.Threading.Tasks;
  35. using System.Reflection;
  36. using System.Net;
  37. using NUnit.Framework;
  38. namespace MonoTests.System.Net
  39. {
  40. [TestFixture]
  41. public class WebClientTestAsync
  42. {
  43. [Test]
  44. [Category("Async")]
  45. public void DownloadData ()
  46. {
  47. SyncContextTest.Run ();
  48. }
  49. [Test]
  50. [Category("Async")]
  51. public void DownloadFileTaskAsync ()
  52. {
  53. WebClient wc = new WebClient ();
  54. string filename = Path.GetTempFileName ();
  55. var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename);
  56. task.Wait ();
  57. Assert.IsTrue (task.IsCompleted);
  58. File.Delete (filename);
  59. }
  60. [Test]
  61. [Category("Async")]
  62. public void Cancelation ()
  63. {
  64. WebClient wc = new WebClient ();
  65. var progress = new ManualResetEvent (false);
  66. wc.DownloadProgressChanged += delegate {
  67. progress.Set ();
  68. };
  69. // Try downloading some large file, so we don't finish early.
  70. var url = "http://download.mono-project.com/archive/2.10.9/macos-10-x86/11/MonoFramework-MDK-2.10.9_11.macos10.xamarin.x86.dmg";
  71. var task = wc.DownloadDataTaskAsync (url);
  72. Assert.IsTrue (progress.WaitOne (10000), "#1");
  73. wc.CancelAsync ();
  74. try {
  75. task.Wait ();
  76. Assert.Fail ("#2");
  77. } catch (Exception ex) {
  78. if (ex is AggregateException)
  79. ex = ((AggregateException)ex).InnerException;
  80. Assert.IsInstanceOfType (typeof (OperationCanceledException), ex, "#3");
  81. Assert.IsTrue (task.IsCanceled, "#4");
  82. }
  83. }
  84. [Test]
  85. [Category("Async")]
  86. public void DownloadMultiple ()
  87. {
  88. WebClient wc = new WebClient ();
  89. var t1 = wc.OpenReadTaskAsync ("http://www.google.com/");
  90. t1.Wait ();
  91. Assert.IsTrue (t1.IsCompleted, "#1");
  92. var t2 = wc.OpenReadTaskAsync ("http://www.mono-project.com/");
  93. t2.Wait ();
  94. Assert.IsTrue (t2.IsCompleted, "#2");
  95. var t3 = wc.DownloadStringTaskAsync ("http://www.google.com/");
  96. t3.Wait ();
  97. Assert.IsTrue (t3.IsCompleted, "#3");
  98. }
  99. private class SyncContextTest
  100. {
  101. SyncContext ctx;
  102. WebClient wc;
  103. bool progress_changed;
  104. bool completed;
  105. bool progress_changed_error;
  106. bool completed_error;
  107. bool done;
  108. bool done_error;
  109. int thread_id;
  110. SyncContextTest ()
  111. {
  112. ctx = new SyncContext ();
  113. wc = new WebClient ();
  114. wc.DownloadProgressChanged += HandleDownloadProgressChanged;
  115. wc.DownloadDataCompleted += HandleDownloadDataCompleted;
  116. }
  117. void HandleDownloadDataCompleted (object sender, DownloadDataCompletedEventArgs e)
  118. {
  119. completed = true;
  120. if (Thread.CurrentThread.ManagedThreadId != thread_id)
  121. completed_error = true;
  122. CheckCompleted ();
  123. }
  124. void HandleDownloadProgressChanged (object sender, DownloadProgressChangedEventArgs e)
  125. {
  126. progress_changed = true;
  127. if (Thread.CurrentThread.ManagedThreadId != thread_id)
  128. progress_changed_error = true;
  129. CheckCompleted ();
  130. }
  131. void CheckCompleted ()
  132. {
  133. if (!progress_changed || !completed || !done)
  134. return;
  135. ThreadPool.QueueUserWorkItem (state => {
  136. Thread.Sleep (250);
  137. ctx.Cancel ();
  138. });
  139. }
  140. void SetupTimeoutHandler ()
  141. {
  142. ThreadPool.QueueUserWorkItem (state => {
  143. Thread.Sleep (30000);
  144. wc.CancelAsync ();
  145. ctx.Cancel ();
  146. });
  147. }
  148. public static void Run ()
  149. {
  150. SyncContextTest test = new SyncContextTest ();
  151. test.DoRun ();
  152. }
  153. void DoRun ()
  154. {
  155. SetupTimeoutHandler ();
  156. var old_ctx = SynchronizationContext.Current;
  157. try {
  158. SynchronizationContext.SetSynchronizationContext (ctx);
  159. thread_id = Thread.CurrentThread.ManagedThreadId;
  160. ctx.Post (obj => DownloadDataAsync (), null);
  161. ctx.RunMessagePump ();
  162. } catch (Exception ex) {
  163. Assert.Fail ("Unknown exception: {0}", ex);
  164. } finally {
  165. SynchronizationContext.SetSynchronizationContext (old_ctx);
  166. }
  167. Assert.IsTrue (progress_changed, "#1");
  168. Assert.IsFalse (progress_changed_error, "#2");
  169. Assert.IsTrue (completed, "#3");
  170. Assert.IsFalse (completed_error, "#4");
  171. Assert.IsTrue (done, "#5");
  172. Assert.IsFalse (done_error, "#6");
  173. }
  174. async void DownloadDataAsync ()
  175. {
  176. var url = Assembly.GetExecutingAssembly ().CodeBase;
  177. await wc.DownloadDataTaskAsync (url);
  178. done = true;
  179. if (Thread.CurrentThread.ManagedThreadId != thread_id)
  180. done_error = true;
  181. CheckCompleted ();
  182. }
  183. }
  184. public class SyncContext : SynchronizationContext
  185. {
  186. private delegate void MyAction ();
  187. private readonly Queue<MyAction> queue = new Queue<MyAction> ();
  188. private readonly object sync = new object ();
  189. private bool running = true;
  190. public override void Send (SendOrPostCallback d, object state)
  191. {
  192. throw new InvalidOperationException ();
  193. }
  194. public override void Post (SendOrPostCallback d, object state)
  195. {
  196. lock (sync) {
  197. queue.Enqueue (() => d (state));
  198. Monitor.Pulse (sync);
  199. }
  200. }
  201. public void RunMessagePump ()
  202. {
  203. while (running) {
  204. MyAction action;
  205. lock (sync) {
  206. while (queue.Count == 0) {
  207. if (!running)
  208. return;
  209. Monitor.Wait (sync);
  210. }
  211. action = queue.Dequeue ();
  212. }
  213. action ();
  214. }
  215. }
  216. public void Cancel ()
  217. {
  218. lock (sync) {
  219. running = false;
  220. Monitor.Pulse (sync);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. #endif