FromEvent.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. #if STRESS
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Reactive.Disposables;
  9. using System.Reactive.Linq;
  10. using System.Reflection;
  11. using System.Threading;
  12. namespace ReactiveTests.Stress.Linq
  13. {
  14. public class FromEvent
  15. {
  16. private static Lazy<Random> s_rand = new Lazy<Random>();
  17. /// <summary>
  18. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  19. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  20. ///
  21. /// Runs a set of combinations of the RefCount_* tests.
  22. /// </summary>
  23. public static void RefCount_Mix()
  24. {
  25. Console.Title = MethodInfo.GetCurrentMethod().Name + " - 0% complete";
  26. for (int i = 1; i <= 100; i++)
  27. {
  28. var repeatCount = 10;
  29. foreach (var msgCount in new[] { 100, 1000, 10000, 100000 })
  30. {
  31. // concurrency level {10, 20, ..., 100}
  32. RefCount_ConcurrencyLevel_Linear(msgCount, repeatCount, 10, 100, 10);
  33. // concurrency level {100, 200, ..., 1000}
  34. RefCount_ConcurrencyLevel_Linear(msgCount, repeatCount, 100, 1000, 100);
  35. // concurrency level {1, 2, 4, ..., 65536}
  36. RefCount_ConcurrencyLevel_Exponential(msgCount, repeatCount, 1, 65536, 2);
  37. }
  38. foreach (var maxMsgCount in new[] { 10, 100, 1000, 10000, 100000 })
  39. {
  40. foreach (var maxConcurrency in new[] { 10, 100, 1000, 10000, 100000 })
  41. {
  42. RefCount_Rand(repeatCount, maxMsgCount, maxConcurrency);
  43. }
  44. }
  45. Console.Title = MethodInfo.GetCurrentMethod().Name + " - " + i + "% complete";
  46. }
  47. }
  48. /// <summary>
  49. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  50. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  51. /// Subscriptions are happening on the ThreadPool, possibly causing (expected) time gaps.
  52. ///
  53. /// Runs a set of combinations of the RefCount_* tests.
  54. /// </summary>
  55. public static void RefCountWithPost_Mix()
  56. {
  57. Console.Title = MethodInfo.GetCurrentMethod().Name + " - 0% complete";
  58. for (int i = 1; i <= 100; i++)
  59. {
  60. var repeatCount = 10;
  61. foreach (var msgCount in new[] { 100, 1000, 10000, 100000 })
  62. {
  63. // concurrency level {10, 20, ..., 100}
  64. RefCountWithPost_ConcurrencyLevel_Linear(msgCount, repeatCount, 10, 100, 10);
  65. // concurrency level {100, 200, ..., 1000}
  66. RefCountWithPost_ConcurrencyLevel_Linear(msgCount, repeatCount, 100, 1000, 100);
  67. // concurrency level {1, 2, 4, ..., 65536}
  68. RefCountWithPost_ConcurrencyLevel_Exponential(msgCount, repeatCount, 1, 65536, 2);
  69. }
  70. foreach (var maxMsgCount in new[] { 10, 100, 1000, 10000, 100000 })
  71. {
  72. foreach (var maxConcurrency in new[] { 10, 100, 1000, 10000, 100000 })
  73. {
  74. RefCountWithPost_Rand(repeatCount, maxMsgCount, maxConcurrency);
  75. }
  76. }
  77. Console.Title = MethodInfo.GetCurrentMethod().Name + " - " + i + "% complete";
  78. }
  79. }
  80. /// <summary>
  81. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  82. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  83. ///
  84. /// Uses random parameters for the number of messages and the level of concurrency.
  85. /// </summary>
  86. /// <param name="n">Number of iterations.</param>
  87. /// <param name="maxN">Maximum number of message.</param>
  88. /// <param name="maxM">Maximum level of concurrency.</param>
  89. public static void RefCount_Rand(int n, int maxN, int maxM)
  90. {
  91. RefCount_(RefCount_Rand_Params(n, maxN, maxM));
  92. }
  93. /// <summary>
  94. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  95. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  96. /// Subscriptions are happening on the ThreadPool, possibly causing (expected) time gaps.
  97. ///
  98. /// Uses random parameters for the number of messages and the level of concurrency.
  99. /// </summary>
  100. /// <param name="n">Number of iterations.</param>
  101. /// <param name="maxN">Maximum number of message.</param>
  102. /// <param name="maxM">Maximum level of concurrency.</param>
  103. public static void RefCountWithPost_Rand(int n, int maxN, int maxM)
  104. {
  105. RefCountWithPost_(RefCount_Rand_Params(n, maxN, maxM));
  106. }
  107. private static IEnumerable<Tuple<int, int>> RefCount_Rand_Params(int n, int maxN, int maxM)
  108. {
  109. for (int i = 0; i < n; i++)
  110. {
  111. var N = s_rand.Value.Next(1, maxN);
  112. var M = s_rand.Value.Next(1, maxM);
  113. yield return new Tuple<int, int>(N, M);
  114. }
  115. }
  116. /// <summary>
  117. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  118. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  119. ///
  120. /// Uses linear increments for the concurrency level.
  121. /// </summary>
  122. /// <param name="N">Number of messages.</param>
  123. /// <param name="n">Number of iterations.</param>
  124. /// <param name="min">Minimum level of concurrency.</param>
  125. /// <param name="max">Maximum level of concurrency.</param>
  126. /// <param name="step">Additive step size to increase level of concurrency.</param>
  127. public static void RefCount_ConcurrencyLevel_Linear(int N, int n, int min, int max, int step)
  128. {
  129. RefCount_(RefCount_ConcurrencyLevel_Linear_Params(N, n, min, max, step));
  130. }
  131. /// <summary>
  132. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  133. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  134. /// Subscriptions are happening on the ThreadPool, possibly causing (expected) time gaps.
  135. ///
  136. /// Uses linear increments for the concurrency level.
  137. /// </summary>
  138. /// <param name="N">Number of messages.</param>
  139. /// <param name="n">Number of iterations.</param>
  140. /// <param name="min">Minimum level of concurrency.</param>
  141. /// <param name="max">Maximum level of concurrency.</param>
  142. /// <param name="step">Additive step size to increase level of concurrency.</param>
  143. public static void RefCountWithPost_ConcurrencyLevel_Linear(int N, int n, int min, int max, int step)
  144. {
  145. RefCountWithPost_(RefCount_ConcurrencyLevel_Linear_Params(N, n, min, max, step));
  146. }
  147. private static IEnumerable<Tuple<int, int>> RefCount_ConcurrencyLevel_Linear_Params(int N, int n, int min, int max, int step)
  148. {
  149. for (int i = 0; i < n; i++)
  150. {
  151. for (int M = min; M <= max; M += step)
  152. {
  153. yield return new Tuple<int, int>(N, M);
  154. }
  155. }
  156. }
  157. /// <summary>
  158. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  159. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  160. ///
  161. /// Uses exponential increments for the concurrency level.
  162. /// </summary>
  163. /// <param name="N">Number of messages.</param>
  164. /// <param name="n">Number of iterations.</param>
  165. /// <param name="min">Minimum level of concurrency.</param>
  166. /// <param name="max">Maximum level of concurrency.</param>
  167. /// <param name="step">Multiplicative step size to increase level of concurrency.</param>
  168. public static void RefCount_ConcurrencyLevel_Exponential(int N, int n, int min, int max, int step)
  169. {
  170. RefCount_(RefCount_ConcurrencyLevel_Exponential_Params(N, n, min, max, step));
  171. }
  172. /// <summary>
  173. /// Multiple threads are subscribing to a FromEventPattern sequence and disposing their subscriptions.
  174. /// While this is going on, one consumer does not want to be disturbed while receiving the sequence.
  175. /// Subscriptions are happening on the ThreadPool, possibly causing (expected) time gaps.
  176. ///
  177. /// Uses exponential increments for the concurrency level.
  178. /// </summary>
  179. /// <param name="N">Number of messages.</param>
  180. /// <param name="n">Number of iterations.</param>
  181. /// <param name="min">Minimum level of concurrency.</param>
  182. /// <param name="max">Maximum level of concurrency.</param>
  183. /// <param name="step">Multiplicative step size to increase level of concurrency.</param>
  184. public static void RefCountWithPost_ConcurrencyLevel_Exponential(int N, int n, int min, int max, int step)
  185. {
  186. RefCountWithPost_(RefCount_ConcurrencyLevel_Exponential_Params(N, n, min, max, step));
  187. }
  188. private static IEnumerable<Tuple<int, int>> RefCount_ConcurrencyLevel_Exponential_Params(int N, int n, int min, int max, int step)
  189. {
  190. for (int i = 0; i < n; i++)
  191. {
  192. for (int M = min; M <= max; M *= step)
  193. {
  194. yield return new Tuple<int, int>(N, M);
  195. }
  196. }
  197. }
  198. private static void RefCount_(IEnumerable<Tuple<int, int>> parameters)
  199. {
  200. foreach (var p in parameters)
  201. {
  202. var N = p.Item1;
  203. var M = p.Item2;
  204. Console.Write("N = {0}, M = {1} - ", N, M);
  205. var bar = new Bar();
  206. var foo = Observable.FromEventPattern<FooEventArgs>(h => { Console.Write("+"); bar.Foo += h; }, h => { bar.Foo -= h; Console.Write("-"); });
  207. var res = new List<int>();
  208. var n = 0;
  209. var e = new ManualResetEvent(false);
  210. var cd = new CountdownEvent(M * 2);
  211. for (int i = 0; i < M; i++)
  212. {
  213. var f = new SingleAssignmentDisposable();
  214. ThreadPool.QueueUserWorkItem(_ =>
  215. {
  216. f.Disposable = foo.Subscribe(__ => { Console.Write("!"); });
  217. cd.Signal();
  218. });
  219. ThreadPool.QueueUserWorkItem(_ =>
  220. {
  221. f.Dispose();
  222. cd.Signal();
  223. });
  224. }
  225. Console.Write("{SB}");
  226. var d = foo.Subscribe(x =>
  227. {
  228. //Console.Write("&");
  229. if (++n == N)
  230. e.Set();
  231. res.Add(x.EventArgs.Qux);
  232. });
  233. Console.Write("{SE}");
  234. var t = new Thread(() =>
  235. {
  236. Console.Write("{TB}");
  237. for (int i = 0; i < N; i++)
  238. bar.OnFoo(i);
  239. Console.Write("{TE}");
  240. });
  241. t.Start();
  242. t.Join();
  243. cd.Wait();
  244. e.WaitOne();
  245. d.Dispose();
  246. if (!res.SequenceEqual(Enumerable.Range(0, N)))
  247. {
  248. Console.WriteLine("Panic!");
  249. break;
  250. }
  251. Console.WriteLine(".");
  252. }
  253. }
  254. private static void RefCountWithPost_(IEnumerable<Tuple<int, int>> parameters)
  255. {
  256. var worker = new Thread(() =>
  257. {
  258. SynchronizationContext.SetSynchronizationContext(new MySyncCtx());
  259. foreach (var p in parameters)
  260. {
  261. var N = p.Item1;
  262. var M = p.Item2;
  263. Console.Write("N = {0}, M = {1} - ", N, M);
  264. var bar = new Bar();
  265. var foo = Observable.FromEventPattern<FooEventArgs>(h => { /*Console.Write("+");*/ bar.Foo += h; }, h => { bar.Foo -= h; /*Console.Write("-"); */});
  266. var e = new ManualResetEvent(false);
  267. var cd = new CountdownEvent(M * 2);
  268. for (int i = 0; i < M; i++)
  269. {
  270. var f = new SingleAssignmentDisposable();
  271. ThreadPool.QueueUserWorkItem(_ =>
  272. {
  273. f.Disposable = foo.Subscribe(__ => { /*Console.Write("!");*/ });
  274. cd.Signal();
  275. });
  276. ThreadPool.QueueUserWorkItem(_ =>
  277. {
  278. f.Dispose();
  279. cd.Signal();
  280. });
  281. }
  282. var hasObserved = 0;
  283. Console.Write("{SB}");
  284. var d = foo.Subscribe(x =>
  285. {
  286. //
  287. // [on BARTDE-M6500 with CPU and RAM pressure]
  288. //
  289. // Up to 8K concurrent observers, we typically don't see a time gap (expected worst-case behavior).
  290. // The code below uses an event to check the desired behavior of eventually tuning in to the event stream.
  291. //
  292. Console.Write("&" + x.EventArgs.Qux);
  293. e.Set();
  294. Interlocked.Exchange(ref hasObserved, 1);
  295. });
  296. Console.Write("{SE}");
  297. var t = new Thread(() =>
  298. {
  299. Console.Write("{TB}");
  300. var i = 0;
  301. while (Thread.VolatileRead(ref hasObserved) == 0)
  302. bar.OnFoo(i++);
  303. Console.Write("{TE}");
  304. });
  305. t.Start();
  306. t.Join();
  307. cd.Wait();
  308. e.WaitOne();
  309. d.Dispose();
  310. Console.WriteLine(".");
  311. }
  312. });
  313. worker.Start();
  314. worker.Join();
  315. }
  316. class Bar
  317. {
  318. public event EventHandler<FooEventArgs> Foo;
  319. public void OnFoo(int x)
  320. {
  321. var foo = Foo;
  322. if (foo != null)
  323. foo(this, new FooEventArgs { Qux = x });
  324. }
  325. }
  326. class FooEventArgs : EventArgs
  327. {
  328. public int Qux { get; set; }
  329. }
  330. class MySyncCtx : SynchronizationContext
  331. {
  332. public override void Post(SendOrPostCallback d, object state)
  333. {
  334. ThreadPool.QueueUserWorkItem(_ =>
  335. {
  336. d(state);
  337. });
  338. }
  339. }
  340. }
  341. }
  342. #endif