File: SchedulerTest.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1089 lines) | stat: -rw-r--r-- 39,682 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.PlatformServices;
using System.Runtime.CompilerServices;
using System.Threading;
#if NUNIT
using NUnit.Framework;
using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using TestMethodAttribute = NUnit.Framework.TestAttribute;
using TestInitializeAttribute = NUnit.Framework.SetUpAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using Microsoft.Reactive.Testing;

#if HAS_WINFORMS
using System.Windows.Forms;
#endif

namespace ReactiveTests.Tests
{
    [TestClass]
    public class SchedulerTest
    {
        #region IScheduler

        [TestMethod]
        public void Scheduler_ArgumentChecks()
        {
            var ms = new MyScheduler();
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), a => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), () => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), 1, (a, s) => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, default(Action<Action>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, 1, default(Action<int, Action<int>>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), DateTimeOffset.Now, a => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), DateTimeOffset.Now, () => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), 1, DateTimeOffset.Now, (a, s) => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, DateTimeOffset.Now, default(Action<Action<DateTimeOffset>>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, 1, DateTimeOffset.Now, default(Action<int, Action<int, DateTimeOffset>>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), TimeSpan.Zero, a => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), TimeSpan.Zero, () => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(default(IScheduler), 1, TimeSpan.Zero, (a, s) => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, TimeSpan.Zero, default(Action<Action<TimeSpan>>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Schedule(ms, 1, TimeSpan.Zero, default(Action<int, Action<int, TimeSpan>>)));
        }

        [TestMethod]
        public void Schedulers_ArgumentChecks()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.CurrentThread.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.CurrentThread.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.CurrentThread.Schedule(DateTimeOffset.MaxValue, default(Action)));
#if !NO_WINDOWS_THREADING
            ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherScheduler.Instance.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherScheduler.Instance.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherScheduler.Instance.Schedule(DateTimeOffset.MaxValue, default(Action)));
#endif
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Immediate.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Immediate.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Immediate.Schedule(DateTimeOffset.MaxValue, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => NewThreadScheduler.Default.Schedule(DateTimeOffset.MaxValue, default(Action)));
#if !NO_TPL
            ReactiveAssert.Throws<ArgumentNullException>(() => TaskPoolScheduler.Default.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => TaskPoolScheduler.Default.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => TaskPoolScheduler.Default.Schedule(DateTimeOffset.MaxValue, default(Action)));
#endif
            ReactiveAssert.Throws<ArgumentNullException>(() => DefaultScheduler.Instance.Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => DefaultScheduler.Instance.Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => DefaultScheduler.Instance.Schedule(DateTimeOffset.MaxValue, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => DefaultScheduler.Instance.SchedulePeriodic(42, TimeSpan.FromSeconds(1), default(Func<int, int>)));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => DefaultScheduler.Instance.SchedulePeriodic(42, TimeSpan.FromSeconds(-1), _ => _));
#if HAS_WINFORMS
            var lbl = new Label();
            ReactiveAssert.Throws<ArgumentNullException>(() => new ControlScheduler(lbl).Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => new ControlScheduler(lbl).Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => new ControlScheduler(lbl).Schedule(DateTimeOffset.MaxValue, default(Action)));
#endif
            var ctx = new SynchronizationContext();
            ReactiveAssert.Throws<ArgumentNullException>(() => new SynchronizationContextScheduler(ctx).Schedule(default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => new SynchronizationContextScheduler(ctx).Schedule(TimeSpan.Zero, default(Action)));
            ReactiveAssert.Throws<ArgumentNullException>(() => new SynchronizationContextScheduler(ctx).Schedule(DateTimeOffset.MaxValue, default(Action)));
        }

        [TestMethod]
        public void Scheduler_ScheduleNonRecursive()
        {
            var ms = new MyScheduler();
            var res = false;
            Scheduler.Schedule(ms, a => { res = true; });
            Assert.IsTrue(res);
        }

        [TestMethod]
        public void Scheduler_ScheduleRecursive()
        {
            var ms = new MyScheduler();
            var i = 0;
            Scheduler.Schedule(ms, a => { if (++i < 10) a(); });
            Assert.AreEqual(10, i);
        }

        [TestMethod]
        public void Scheduler_ScheduleWithTimeNonRecursive()
        {
            var now = DateTimeOffset.Now;
            var ms = new MyScheduler(now) { Check = (a, s, t) => { Assert.IsTrue(t == TimeSpan.Zero); } };
            var res = false;
            Scheduler.Schedule(ms, now, a => { res = true; });
            Assert.IsTrue(res);
            Assert.IsTrue(ms.WaitCycles == 0);
        }

        [TestMethod]
        public void Scheduler_ScheduleWithTimeRecursive()
        {
            var now = DateTimeOffset.Now;
            var i = 0;
            var ms = new MyScheduler(now) { Check = (a, s, t) => { Assert.IsTrue(t == TimeSpan.Zero); } };
            Scheduler.Schedule(ms, now, a => { if (++i < 10) a(now); });
            Assert.IsTrue(ms.WaitCycles == 0);
            Assert.AreEqual(10, i);
        }

        [TestMethod]
        public void Scheduler_ScheduleWithTimeSpanNonRecursive()
        {
            var now = DateTimeOffset.Now;
            var ms = new MyScheduler(now) { Check = (a, s, t) => { Assert.IsTrue(t == TimeSpan.Zero); } };
            var res = false;
            Scheduler.Schedule(ms, TimeSpan.Zero, a => { res = true; });
            Assert.IsTrue(res);
            Assert.IsTrue(ms.WaitCycles == 0);
        }

        [TestMethod]
        public void Scheduler_ScheduleWithTimeSpanRecursive()
        {
            var now = DateTimeOffset.Now;
            var ms = new MyScheduler(now) { Check = (a, s, t) => { Assert.IsTrue(t < TimeSpan.FromTicks(10)); } };
            var i = 0;
            Scheduler.Schedule(ms, TimeSpan.Zero, a => { if (++i < 10) a(TimeSpan.FromTicks(i)); });
            Assert.IsTrue(ms.WaitCycles == Enumerable.Range(1, 9).Sum());
            Assert.AreEqual(10, i);
        }

        [TestMethod]
        public void Scheduler_StateThreading()
        {
            var lst = new List<int>();
            Scheduler.Immediate.Schedule(0, (i, a) =>
            {
                lst.Add(i);
                if (i < 9)
                    a(i + 1);
            });

            Assert.IsTrue(lst.SequenceEqual(Enumerable.Range(0, 10)));
        }

        [TestMethod]
        public void Scheduler_Builtins()
        {
            // Default
            {
                var e = new ManualResetEvent(false);
                Scheduler.Default.Schedule(() => e.Set());
                e.WaitOne();
            }

            if (!Utils.IsRunningWithPortableLibraryBinaries())
            {
                Scheduler_Builtins_NoPlib();
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private void Scheduler_Builtins_NoPlib()
        {
#if !PLIB
            // ThreadPool
            {
                var e = new ManualResetEvent(false);
                Scheduler.ThreadPool.Schedule(() => e.Set());
                e.WaitOne();
            }
#endif

#if !NO_THREAD
            // NewThread
            {
                var e = new ManualResetEvent(false);
                Scheduler.NewThread.Schedule(() => e.Set());
                e.WaitOne();
            }
#endif

#if !NO_TPL
            // TaskPool
            {
                var e = new ManualResetEvent(false);
                Scheduler.TaskPool.Schedule(() => e.Set());
                e.WaitOne();
            }
#endif
        }

        #endregion

        #region ISchedulerLongRunning

#if !NO_PERF
        [TestMethod]
        public void Scheduler_LongRunning_ArgumentChecking()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.ScheduleLongRunning(null, c => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.ScheduleLongRunning(ThreadPoolScheduler.Instance, default(Action<ICancelable>)));
        }

        [TestMethod]
        public void Scheduler_Periodic_ArgumentChecking()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic(null, TimeSpan.FromSeconds(1), () => { }));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => Scheduler.SchedulePeriodic(ThreadPoolScheduler.Instance, TimeSpan.FromSeconds(-1), () => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic(ThreadPoolScheduler.Instance, TimeSpan.FromSeconds(1), default(Action)));

            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic<int>(null, 42, TimeSpan.FromSeconds(1), _ => { }));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => Scheduler.SchedulePeriodic<int>(ThreadPoolScheduler.Instance, 42, TimeSpan.FromSeconds(-1), _ => { }));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic<int>(ThreadPoolScheduler.Instance, 42, TimeSpan.FromSeconds(1), default(Action<int>)));

            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic<int>(null, 42, TimeSpan.FromSeconds(1), _ => _));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => Scheduler.SchedulePeriodic<int>(ThreadPoolScheduler.Instance, 42, TimeSpan.FromSeconds(-1), _ => _));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.SchedulePeriodic<int>(ThreadPoolScheduler.Instance, 42, TimeSpan.FromSeconds(1), default(Func<int, int>)));
        }

        [TestMethod]
        public void Scheduler_Stopwatch_Emulation()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.StartStopwatch(null));
        }

#if !NO_TPL
        [TestMethod]
        public void Scheduler_LongRunning1()
        {
            var s = TaskPoolScheduler.Default;

            var x = new ManualResetEvent(false);
            var e = new ManualResetEvent(false);

            var d = s.ScheduleLongRunning(42, (state, cancel) =>
            {
                while (!cancel.IsDisposed)
                    x.Set();
                e.Set();
            });

            x.WaitOne();
            d.Dispose();

            e.WaitOne();
        }

        [TestMethod]
        public void Scheduler_LongRunning2()
        {
            var s = TaskPoolScheduler.Default;

            var x = new ManualResetEvent(false);
            var e = new ManualResetEvent(false);

            var d = s.ScheduleLongRunning(cancel =>
            {
                while (!cancel.IsDisposed)
                    x.Set();
                e.Set();
            });

            x.WaitOne();
            d.Dispose();

            e.WaitOne();
        }
#endif
#endif

        #endregion

        #region ISchedulerPeriodic

#if !NO_PERF
        [TestMethod]
        public void Scheduler_Periodic1()
        {
            var n = 0;
            var e = new ManualResetEvent(false);

            var d = ThreadPoolScheduler.Instance.SchedulePeriodic(TimeSpan.FromMilliseconds(50), () =>
            {
                if (n++ == 10)
                    e.Set();
            });

            e.WaitOne();
            d.Dispose();
        }

        [TestMethod]
        public void Scheduler_Periodic2()
        {
            var n = 0;
            var e = new ManualResetEvent(false);

            var d = ThreadPoolScheduler.Instance.SchedulePeriodic(42, TimeSpan.FromMilliseconds(50), x =>
            {
                Assert.AreEqual(42, x);

                if (n++ == 10)
                    e.Set();
            });

            e.WaitOne();
            d.Dispose();
        }

#if DESKTOPCLR
        [TestMethod]
        public void Scheduler_Periodic_HostLifecycleManagement()
        {
            var cur = Utils.GetTestBaseDirectory();

            var domain = AppDomain.CreateDomain("HLN", null, new AppDomainSetup { ApplicationBase = cur });

            domain.DoCallBack(() =>
            {
                var pep = PlatformEnlightenmentProvider.Current;

                try
                {
                    var hln = new HLN();
                    PlatformEnlightenmentProvider.Current = new PEP(hln);

                    var s = ThreadPoolScheduler.Instance.DisableOptimizations(typeof(ISchedulerPeriodic));

                    var n = 0;
                    var e = new ManualResetEvent(false);

                    var d = Observable.Interval(TimeSpan.FromMilliseconds(100), s).Subscribe(_ =>
                    {
                        if (n++ == 10)
                            e.Set();
                    });

                    hln.OnSuspending();
                    hln.OnResuming();

                    Thread.Sleep(250);
                    hln.OnSuspending();

                    Thread.Sleep(150);
                    hln.OnResuming();

                    Thread.Sleep(50);
                    hln.OnSuspending();
                    hln.OnResuming();

                    e.WaitOne();
                    d.Dispose();
                }
                finally
                {
                    PlatformEnlightenmentProvider.Current = pep;
                }
            });
        }

        class PEP : IPlatformEnlightenmentProvider
        {
            private readonly IPlatformEnlightenmentProvider _old;
            private readonly IHostLifecycleNotifications _hln;

            public PEP(HLN hln)
            {
                _old = PlatformEnlightenmentProvider.Current;
                _hln = hln;
            }

            public T GetService<T>(params object[] args) where T : class
            {
                if (typeof(T) == typeof(IHostLifecycleNotifications))
                {
                    return (T)(object)_hln;
                }

                return _old.GetService<T>(args);
            }
        }

        class HLN : IHostLifecycleNotifications
        {
            public event EventHandler<HostSuspendingEventArgs> Suspending;
            public event EventHandler<HostResumingEventArgs> Resuming;

            public void OnSuspending()
            {
                var s = Suspending;
                if (s != null)
                    s(this, null);
            }

            public void OnResuming()
            {
                var s = Resuming;
                if (s != null)
                    s(this, null);
            }
        }
#endif

#endif

        #endregion

        #region DisableOptimizations

#if !NO_PERF
        [TestMethod]
        public void DisableOptimizations_ArgumentChecking()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(default(IScheduler)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(default(IScheduler), new Type[0]));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(ThreadPoolScheduler.Instance, default(Type[])));

            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(Scheduler.Default).Schedule(42, default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(Scheduler.Default).Schedule(42, TimeSpan.FromSeconds(1), default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.DisableOptimizations(Scheduler.Default).Schedule(42, DateTimeOffset.Now, default(Func<IScheduler, int, IDisposable>)));
        }

#if !NO_TPL
        [TestMethod]
        public void DisableOptimizations1()
        {
            var s = TaskPoolScheduler.Default;
            Assert.IsTrue(s is IServiceProvider);

            var t = s.DisableOptimizations();

            var d = t.Now - s.Now;
            Assert.IsTrue(d.TotalSeconds < 1);

            var e1 = new ManualResetEvent(false);
            t.Schedule(42, (self, state) =>
            {
                e1.Set();
                return Disposable.Empty;
            });
            e1.WaitOne();

            var e2 = new ManualResetEvent(false);
            t.Schedule(42, TimeSpan.FromMilliseconds(1), (self, state) =>
            {
                e2.Set();
                return Disposable.Empty;
            });
            e2.WaitOne();

            var e3 = new ManualResetEvent(false);
            t.Schedule(42, DateTimeOffset.Now.AddMilliseconds(10), (self, state) =>
            {
                e3.Set();
                return Disposable.Empty;
            });
            e3.WaitOne();
        }

        [TestMethod]
        public void DisableOptimizations2()
        {
            var s = TaskPoolScheduler.Default;
            Assert.IsTrue(s is IServiceProvider);

            var lr1 = ((IServiceProvider)s).GetService(typeof(ISchedulerLongRunning));
            Assert.IsNotNull(lr1);

            var e1 = new ManualResetEvent(false);
            s.Schedule(42, (self, state) =>
            {
                Assert.IsTrue(self is IServiceProvider);

                var lrr1 = ((IServiceProvider)self).GetService(typeof(ISchedulerLongRunning));
                Assert.IsNotNull(lrr1);

                e1.Set();
                return Disposable.Empty;
            });
            e1.WaitOne();

            var t = s.DisableOptimizations();
            Assert.IsTrue(t is IServiceProvider);

            var lr2 = ((IServiceProvider)t).GetService(typeof(ISchedulerLongRunning));
            Assert.IsNull(lr2);

            var e2 = new ManualResetEvent(false);
            t.Schedule(42, (self, state) =>
            {
                Assert.IsTrue(self is IServiceProvider);

                var lrr2 = ((IServiceProvider)self).GetService(typeof(ISchedulerLongRunning));
                Assert.IsNull(lrr2);

                e2.Set();
                return Disposable.Empty;
            });
            e2.WaitOne();
        }

        [TestMethod]
        public void DisableOptimizations3()
        {
            var s = TaskPoolScheduler.Default;
            Assert.IsTrue(s is IServiceProvider);

            var lr1 = ((IServiceProvider)s).GetService(typeof(ISchedulerLongRunning));
            Assert.IsNotNull(lr1);

            var p1 = ((IServiceProvider)s).GetService(typeof(ISchedulerPeriodic));
            Assert.IsNotNull(p1);

            var e1 = new ManualResetEvent(false);
            s.Schedule(42, (self, state) =>
            {
                Assert.IsTrue(self is IServiceProvider);

                var lrr1 = ((IServiceProvider)self).GetService(typeof(ISchedulerLongRunning));
                Assert.IsNotNull(lrr1);

                var pr1 = ((IServiceProvider)self).GetService(typeof(ISchedulerPeriodic));
                Assert.IsNotNull(pr1);

                e1.Set();
                return Disposable.Empty;
            });
            e1.WaitOne();

            var t = s.DisableOptimizations(typeof(ISchedulerLongRunning));
            Assert.IsTrue(t is IServiceProvider);

            var lr2 = ((IServiceProvider)t).GetService(typeof(ISchedulerLongRunning));
            Assert.IsNull(lr2);

            var p2 = ((IServiceProvider)t).GetService(typeof(ISchedulerPeriodic));
            Assert.IsNotNull(p2);

            var e2 = new ManualResetEvent(false);
            t.Schedule(42, (self, state) =>
            {
                Assert.IsTrue(self is IServiceProvider);

                var lrr2 = ((IServiceProvider)self).GetService(typeof(ISchedulerLongRunning));
                Assert.IsNull(lrr2);

                var pr2 = ((IServiceProvider)self).GetService(typeof(ISchedulerPeriodic));
                Assert.IsNotNull(pr2);

                e2.Set();
                return Disposable.Empty;
            });
            e2.WaitOne();
        }
#endif
#endif

        [TestMethod]
        public void DisableOptimizations_UnknownService()
        {
            var s = new MyScheduler();
            Assert.IsFalse(s is IServiceProvider);

            var d = s.DisableOptimizations();
            Assert.IsTrue(d is IServiceProvider);
            Assert.IsNull(((IServiceProvider)d).GetService(typeof(bool)));
        }

        class MyScheduler : IScheduler
        {
            public MyScheduler()
                : this(DateTimeOffset.Now)
            {
            }

            public MyScheduler(DateTimeOffset now)
            {
                Now = now;
            }

            public DateTimeOffset Now
            {
                get;
                private set;
            }

            public IDisposable Schedule<T>(T state, Func<IScheduler, T, IDisposable> action)
            {
                return action(this, state);
            }

            public Action<Action<object>, object, TimeSpan> Check { get; set; }
            public long WaitCycles { get; set; }

            public IDisposable Schedule<T>(T state, TimeSpan dueTime, Func<IScheduler, T, IDisposable> action)
            {
                Check(o => action(this, (T)o), state, dueTime);
                WaitCycles += dueTime.Ticks;
                return action(this, state);
            }

            public IDisposable Schedule<T>(T state, DateTimeOffset dueTime, Func<IScheduler, T, IDisposable> action)
            {
                return Schedule(state, dueTime - Now, action);
            }
        }

        #endregion

        #region Catch

        [TestMethod]
        public void Catch_ArgumentChecking()
        {
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Catch<Exception>(default(IScheduler), _ => true));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Catch<Exception>(Scheduler.Default, default(Func<Exception, bool>)));

            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Catch<Exception>(Scheduler.Default, _ => true).Schedule(42, default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Catch<Exception>(Scheduler.Default, _ => true).Schedule(42, TimeSpan.FromSeconds(1), default(Func<IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws<ArgumentNullException>(() => Scheduler.Catch<Exception>(Scheduler.Default, _ => true).Schedule(42, DateTimeOffset.Now, default(Func<IScheduler, int, IDisposable>)));
        }

        [TestMethod]
        public void Catch_Builtin_Swallow_Shallow()
        {
            var done = new ManualResetEvent(false);

            var swallow = Scheduler.Default.Catch<InvalidOperationException>(_ => { done.Set(); return true; });

            swallow.Schedule(() =>
            {
                throw new InvalidOperationException();
            });

            done.WaitOne();
        }

        [TestMethod]
        public void Catch_Builtin_Swallow_Recursive()
        {
            var done = new ManualResetEvent(false);

            var swallow = Scheduler.Default.Catch<InvalidOperationException>(_ => { done.Set(); return true; });

            swallow.Schedule(42, (self, state) =>
            {
                return self.Schedule(() =>
                {
                    throw new InvalidOperationException();
                });
            });

            done.WaitOne();
        }

        [TestMethod]
        public void Catch_Custom_Unhandled()
        {
            var err = default(Exception);
            var scheduler = new MyExceptionScheduler(ex_ => err = ex_);

            scheduler.Catch<InvalidOperationException>(_ => true).Schedule(() =>
            {
                throw new InvalidOperationException();
            });
            Assert.IsNull(err);

            var ex = new ArgumentException();
            scheduler.Catch<InvalidOperationException>(_ => true).Schedule(() =>
            {
                throw ex;
            });
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_Rethrow()
        {
            var err = default(Exception);
            var scheduler = new MyExceptionScheduler(ex_ => err = ex_);

            var ex = new InvalidOperationException();
            scheduler.Catch<InvalidOperationException>(_ => false).Schedule(() =>
            {
                throw ex;
            });
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_LongRunning_Caught()
        {
            var err = default(Exception);
            var scheduler = new MyExceptionScheduler(ex_ => err = ex_);

            var caught = false;
            var @catch = scheduler.Catch<InvalidOperationException>(_ => caught = true);
            var slr = (ISchedulerLongRunning)((IServiceProvider)@catch).GetService(typeof(ISchedulerLongRunning));

            slr.ScheduleLongRunning(cancel =>
            {
                throw new InvalidOperationException();
            });
            Assert.IsTrue(caught);
            Assert.IsNull(err);

            var ex = new ArgumentException();
            slr.ScheduleLongRunning(cancel =>
            {
                throw ex;
            });
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_LongRunning_Rethrow()
        {
            var err = default(Exception);
            var scheduler = new MyExceptionScheduler(ex_ => err = ex_);

            var @catch = scheduler.Catch<InvalidOperationException>(_ => false);
            var slr = (ISchedulerLongRunning)((IServiceProvider)@catch).GetService(typeof(ISchedulerLongRunning));

            var done = false;
            slr.ScheduleLongRunning(cancel =>
            {
                done = true;
            });
            Assert.IsTrue(done);

            var ex = new InvalidOperationException();
            slr.ScheduleLongRunning(cancel =>
            {
                throw ex;
            });
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_Periodic_Regular()
        {
            var scheduler = new MyExceptionScheduler(_ => { });
            scheduler.PeriodicStopped = new ManualResetEvent(false);

            var @catch = scheduler.Catch<InvalidOperationException>(_ => true);
            var per = (ISchedulerPeriodic)((IServiceProvider)@catch).GetService(typeof(ISchedulerPeriodic));

            var madeProgress = new ManualResetEvent(false);
            var d = per.SchedulePeriodic(0, TimeSpan.Zero, x =>
            {
                if (x > 10)
                    madeProgress.Set();

                return x + 1;
            });

            madeProgress.WaitOne();
            d.Dispose();
            scheduler.PeriodicStopped.WaitOne();
        }

        [TestMethod]
        public void Catch_Custom_Periodic_Uncaught1()
        {
            var err = default(Exception);
            var done = new ManualResetEvent(false);
            var scheduler = new MyExceptionScheduler(ex_ => { err = ex_; done.Set(); });
            scheduler.PeriodicStopped = new ManualResetEvent(false);

            var @catch = scheduler.Catch<InvalidOperationException>(_ => true);
            var per = (ISchedulerPeriodic)((IServiceProvider)@catch).GetService(typeof(ISchedulerPeriodic));

            var ex = new ArgumentException();
            per.SchedulePeriodic(42, TimeSpan.Zero, x =>
            {
                throw ex;
            });

            scheduler.PeriodicStopped.WaitOne();
            done.WaitOne();
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_Periodic_Uncaught2()
        {
            var err = default(Exception);
            var done = new ManualResetEvent(false);
            var scheduler = new MyExceptionScheduler(ex_ => { err = ex_; done.Set(); });
            scheduler.PeriodicStopped = new ManualResetEvent(false);

            var @catch = scheduler.Catch<InvalidOperationException>(_ => false);
            var per = (ISchedulerPeriodic)((IServiceProvider)@catch).GetService(typeof(ISchedulerPeriodic));

            var ex = new InvalidOperationException();
            per.SchedulePeriodic(42, TimeSpan.Zero, x =>
            {
                throw ex;
            });

            scheduler.PeriodicStopped.WaitOne();
            done.WaitOne();
            Assert.AreSame(ex, err);
        }

        [TestMethod]
        public void Catch_Custom_Periodic_Caught()
        {
            var err = default(Exception);
            var scheduler = new MyExceptionScheduler(ex_ => err = ex_);
            scheduler.PeriodicStopped = new ManualResetEvent(false);

            var caught = new ManualResetEvent(false);
            var @catch = scheduler.Catch<InvalidOperationException>(_ => { caught.Set(); return true; });
            var per = (ISchedulerPeriodic)((IServiceProvider)@catch).GetService(typeof(ISchedulerPeriodic));

            per.SchedulePeriodic(42, TimeSpan.Zero, x =>
            {
                throw new InvalidOperationException();
            });

            scheduler.PeriodicStopped.WaitOne();
            caught.WaitOne();
            Assert.IsNull(err);
        }

        class MyExceptionScheduler : LocalScheduler, ISchedulerLongRunning, ISchedulerPeriodic
        {
            private readonly Action<Exception> _onError;

            public MyExceptionScheduler(Action<Exception> onError)
            {
                _onError = onError;
            }

            public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
            {
                try
                {
                    return action(this, state);
                }
                catch (Exception exception)
                {
                    _onError(exception);
                    return Disposable.Empty;
                }
            }

            public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
            {
                var b = new BooleanDisposable();

                try
                {
                    action(state, b);
                }
                catch (Exception exception)
                {
                    _onError(exception);
                    return Disposable.Empty;
                }

                return b;
            }

            public ManualResetEvent PeriodicStopped { get; set; }

            public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
            {
                var b = new BooleanDisposable();

                Scheduler.Default.Schedule(() =>
                {
                    try
                    {
                        var s = state;
                        for (int i = 0; true; i++)
                        {
                            if (i > 100 /* mimic delayed cancellation */ && b.IsDisposed)
                                break;
                            s = action(s);
                        }
                    }
                    catch (Exception exception)
                    {
                        _onError(exception);
                    }
                    finally
                    {
                        PeriodicStopped.Set();
                    }
                });

                return b;
            }
        }

        #endregion

        #region Services

        [TestMethod]
        public void InvalidService_Null()
        {
            var s = new MySchedulerWithoutServices();
            Assert.IsNull(((IServiceProvider)s).GetService(typeof(IAsyncResult)));
        }

        class MySchedulerWithoutServices : LocalScheduler
        {
            public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }
        }

        [TestMethod]
        public void DetectServices_Null_1()
        {
            var s = new MyDumbScheduler1();
            Assert.IsNull(Scheduler.AsLongRunning(s));
            Assert.IsNull(Scheduler.AsPeriodic(s));
            Assert.IsNull(Scheduler.AsStopwatchProvider(s));
        }

        class MyDumbScheduler1 : IScheduler
        {
            public DateTimeOffset Now
            {
                get { throw new NotImplementedException(); }
            }

            public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }
        }

        [TestMethod]
        public void DetectServices_Null_2()
        {
            var s = new MyDumbScheduler2(new Dictionary<Type, object>());
            Assert.IsNull(Scheduler.AsLongRunning(s));
            Assert.IsNull(Scheduler.AsPeriodic(s));
            Assert.IsNull(Scheduler.AsStopwatchProvider(s));
        }

        [TestMethod]
        public void DetectServices_Found()
        {
            {
                var x = new MyLongRunning();

                var s = new MyDumbScheduler2(new Dictionary<Type, object>
                {
                    { typeof(ISchedulerLongRunning), x }
                });

                Assert.AreEqual(x, Scheduler.AsLongRunning(s));
            }

            {
                var x = new MyStopwatchProvider();

                var s = new MyDumbScheduler2(new Dictionary<Type, object>
                {
                    { typeof(IStopwatchProvider), x }
                });

                Assert.AreEqual(x, Scheduler.AsStopwatchProvider(s));
            }

            {
                var x = new MyPeriodic();

                var s = new MyDumbScheduler2(new Dictionary<Type, object>
                {
                    { typeof(ISchedulerPeriodic), x }
                });

                Assert.AreEqual(x, Scheduler.AsPeriodic(s));
            }
        }

        class MyDumbScheduler2 : IScheduler, IServiceProvider
        {
            private readonly Dictionary<Type, object> _services;

            public MyDumbScheduler2(Dictionary<Type, object> services)
            {
                _services = services;
            }

            public DateTimeOffset Now
            {
                get { throw new NotImplementedException(); }
            }

            public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
            {
                throw new NotImplementedException();
            }

            public object GetService(Type serviceType)
            {
                var res = default(object);
                if (_services.TryGetValue(serviceType, out res))
                    return res;

                return null;
            }
        }

        class MyLongRunning : ISchedulerLongRunning
        {
            public IDisposable ScheduleLongRunning<TState>(TState state, Action<TState, ICancelable> action)
            {
                throw new NotImplementedException();
            }
        }

        class MyStopwatchProvider : IStopwatchProvider
        {
            public IStopwatch StartStopwatch()
            {
                throw new NotImplementedException();
            }
        }

        class MyPeriodic : ISchedulerPeriodic
        {
            public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action)
            {
                throw new NotImplementedException();
            }
        }

        #endregion
    }
}