2 // System.Net.WebClientTestAsync
5 // Martin Baulig (martin.baulig@googlemail.com)
7 // Copyright 2012 Xamarin Inc. (http://www.xamarin.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections.Generic;
33 using System.Threading;
34 using System.Threading.Tasks;
35 using System.Reflection;
37 using NUnit.Framework;
39 namespace MonoTests.System.Net
42 public class WebClientTestAsync
46 public void DownloadData ()
49 bool progress_changed = false;
50 bool completed = false;
51 bool progress_changed_error = false;
52 bool completed_error = false;
54 int thread_id = Thread.CurrentThread.ManagedThreadId;
56 wc = new WebClient ();
58 wc.DownloadProgressChanged += delegate {
59 progress_changed = true;
60 if (Thread.CurrentThread.ManagedThreadId != thread_id)
61 progress_changed_error = true;
63 wc.DownloadDataCompleted += delegate {
65 if (Thread.CurrentThread.ManagedThreadId != thread_id)
66 completed_error = true;
69 MessagePumpSyncContext.Run (async () => {
70 var url = Assembly.GetExecutingAssembly ().CodeBase;
71 await wc.DownloadDataTaskAsync (url);
72 Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, thread_id);
73 }, () => progress_changed && completed, 10000);
75 Assert.IsTrue (progress_changed, "#1");
76 Assert.IsFalse (progress_changed_error, "#2");
77 Assert.IsTrue (completed, "#3");
78 Assert.IsFalse (completed_error, "#4");
82 [Category("InetAccess")]
83 public void DownloadFileTaskAsync ()
85 WebClient wc = new WebClient ();
86 string filename = Path.GetTempFileName ();
88 var task = wc.DownloadFileTaskAsync ("http://www.mono-project.com/", filename);
89 Assert.IsTrue (task.Wait (15000));
90 Assert.IsTrue (task.IsCompleted);
92 File.Delete (filename);
96 [Category("InetAccess")]
97 public void Cancellation ()
99 WebClient wc = new WebClient ();
100 var progress = new ManualResetEvent (false);
101 wc.DownloadProgressChanged += delegate {
105 // Try downloading some large file, so we don't finish early.
106 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";
107 var task = wc.DownloadDataTaskAsync (url);
108 Assert.IsTrue (progress.WaitOne (15000), "#1");
114 } catch (Exception ex) {
115 if (ex is AggregateException)
116 ex = ((AggregateException)ex).InnerException;
117 Assert.That (ex is WebException || ex is OperationCanceledException, "#4");
118 Assert.IsTrue (task.IsCanceled || task.IsFaulted, "#5");
123 [Category("InetAccess")]
124 public void DownloadMultiple ()
126 WebClient wc = new WebClient ();
127 var t1 = wc.OpenReadTaskAsync ("http://www.google.com/");
128 Assert.That (t1.Wait (15000));
129 Assert.IsTrue (t1.IsCompleted, "#1");
131 var t2 = wc.OpenReadTaskAsync ("http://www.mono-project.com/");
132 Assert.That (t2.Wait (15000));
133 Assert.IsTrue (t2.IsCompleted, "#2");
135 var t3 = wc.DownloadStringTaskAsync ("http://www.google.com/");
136 Assert.That (t3.Wait (15000));
137 Assert.IsTrue (t3.IsCompleted, "#3");
141 [Category("InetAccess")]
142 public void DownloadMultiple2 ()
144 WebClient wc = new WebClient ();
146 MessagePumpSyncContext.Run (async () => {
147 await wc.DownloadStringTaskAsync ("http://www.google.com/");
148 await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
153 [Category("InetAccess")]
154 public void DownloadMultiple3 ()
156 WebClient wc = new WebClient ();
157 int thread_id = Thread.CurrentThread.ManagedThreadId;
158 bool data_completed = false;
159 bool string_completed = false;
162 wc.DownloadDataCompleted += delegate {
163 if (data_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
165 data_completed = true;
167 wc.DownloadStringCompleted += delegate {
168 if (string_completed || (Thread.CurrentThread.ManagedThreadId != thread_id))
170 string_completed = true;
173 MessagePumpSyncContext.Run (async () => {
174 await wc.DownloadStringTaskAsync ("http://www.google.com/");
175 await wc.DownloadDataTaskAsync ("http://www.mono-project.com/");
176 }, () => data_completed && string_completed, 15000);
178 Assert.IsTrue (data_completed, "#1");
179 Assert.IsTrue (string_completed, "#2");
180 Assert.IsFalse (error, "#3");
183 public sealed class MessagePumpSyncContext : SynchronizationContext
185 private delegate void MyAction ();
187 private readonly Queue<MyAction> queue = new Queue<MyAction> ();
188 private readonly object sync = new object ();
189 private readonly Func<bool> completed;
190 private readonly int timeout;
191 private bool running = true;
193 MessagePumpSyncContext (Func<bool> completed, int timeout)
195 this.completed = completed;
196 this.timeout = timeout;
199 public override void Send (SendOrPostCallback d, object state)
201 throw new InvalidOperationException ();
204 public override void Post (SendOrPostCallback d, object state)
207 queue.Enqueue (() => d (state));
208 Monitor.Pulse (sync);
216 if (completed != null)
222 void RunMessagePump ()
227 while (queue.Count == 0) {
230 if (!Monitor.Wait (sync, timeout))
231 throw new TimeoutException ();
233 action = queue.Dequeue ();
239 public void Cancel ()
243 Monitor.Pulse (sync);
247 public static void Run (Func<Task> action, Func<bool> completed, int timeout)
249 var old_ctx = SynchronizationContext.Current;
251 var ctx = new MessagePumpSyncContext (completed, timeout);
253 SynchronizationContext.SetSynchronizationContext (ctx);
255 var thread_id = Thread.CurrentThread.ManagedThreadId;
257 var task = action ();
258 task.ContinueWith ((t) => {
260 }, TaskScheduler.FromCurrentSynchronizationContext ());
262 ctx.RunMessagePump ();
265 throw task.Exception;
267 SynchronizationContext.SetSynchronizationContext (old_ctx);