File: control.fs

package info (click to toggle)
fsharp 4.0.0.4%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 58,824 kB
  • ctags: 1,395
  • sloc: cs: 2,983; ml: 1,098; makefile: 410; sh: 409; xml: 113
file content (2107 lines) | stat: -rw-r--r-- 81,016 bytes parent folder | download | duplicates (2)
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
// #Regression #Conformance #ComputationExpressions #Async #Regression #Events #Stress
#if ALL_IN_ONE
module Core_control
#endif
#light

#if NetCore
open System.Threading.Tasks
#endif

#nowarn "40" // recursive references

let biggerThanTrampoliningLimit = 10000

let failuresFile =
   let f = 
        System.Environment.GetEnvironmentVariable("CONTROL_FAILURES_LOG")
   match f with
   | "" | null -> "failures.log"
   | _ -> f

let log msg = 
  printfn "%s" msg
#if GenEqBug
  System.IO.File.AppendAllText(failuresFile, sprintf "%A: %s\r\n" System.DateTime.Now msg)
#endif

let mutable failures = []
let syncObj = new obj()
let report_failure s = 
  stderr.WriteLine " NO"; 
  lock syncObj (fun () ->
     failures <- s :: failures;
     log (sprintf "FAILURE: %s failed" s)
  )

#if Portable
#else
System.AppDomain.CurrentDomain.UnhandledException.AddHandler(
       fun _ (args:System.UnhandledExceptionEventArgs) ->
          lock syncObj (fun () ->
                let e = args.ExceptionObject :?> System.Exception
                printfn "Exception: %s at %s" (e.ToString()) e.StackTrace
                failures <- (args.ExceptionObject :?> System.Exception).ToString() :: failures
             )
)
#endif

let test s b = stderr.Write(s:string);  if b then stderr.WriteLine " OK" else report_failure s 

let checkQuiet s x1 x2 = 
    if x1 <> x2 then 
        (test s false; 
         log (sprintf "expected: %A, got %A" x2 x1))

let check s x1 x2 = 
    if x1 = x2 then test s true
    else (test s false; log (sprintf "expected: %A, got %A" x2 x1))

#if NetCore
#else
let argv = System.Environment.GetCommandLineArgs() 
let SetCulture() = 
  if argv.Length > 2 && argv.[1] = "--culture" then  begin
    let cultureString = argv.[2] in 
    let culture = new System.Globalization.CultureInfo(cultureString) in 
    stdout.WriteLine ("Running under culture "+culture.ToString()+"...");
    System.Threading.Thread.CurrentThread.CurrentCulture <-  culture
  end 
  
do SetCulture()    
#endif

open Microsoft.FSharp.Control
open Microsoft.FSharp.Control.WebExtensions

let boxed(a:Async<'b>) : Async<obj> = async { let! res = a in return box res }

type Microsoft.FSharp.Control.Async with 
        static member Parallel2 (a:Async<'T1>,b:Async<'T2>) =
            async { let! res = Async.Parallel [boxed a; boxed b]
                    return (unbox<'T1>(res.[0]), unbox<'T2>(res.[1])) }

        static member Parallel3 (a:Async<'T1>,b:Async<'T2>,c:Async<'T3>) =
            async { let! res = Async.Parallel [boxed a; boxed b; boxed c]
                    return (unbox<'T1>(res.[0]), unbox<'T2>(res.[1]), unbox<'T3>(res.[2])) }

        static member Generate (n,f, ?numChunks) : Async<'T array> =
            async { let procs = defaultArg numChunks System.Environment.ProcessorCount
                    let resArray = Array.zeroCreate n
                    let! res = Async.Parallel
                                  [ for pid in 0 .. procs-1 ->
                                        async { for i in 0 .. (n/procs+(if n%procs > pid then 1 else 0)) - 1 do
                                                    let elem = (i + pid * (n/procs) + min (n%procs) pid)
                                                    let! res = f elem
                                                    do resArray.[elem] <- res;  } ]
                    return resArray }

module BasicTests = 
  let Run() =
    check "cew23242g" (Async.RunSynchronously (async { do () })) ()
    check "32o8f43k1" (Async.RunSynchronously (async { return () })) ()
    check "32o8f43k2" (Async.RunSynchronously (async { return 1 })) 1

    check "32o8f43k3" (Async.RunSynchronously (async { return 1 })) 1

    check "32o8f43k9" (Async.RunSynchronously (async { do! Async.Sleep(30) 
                                                       return 1 })) 1

    check "32o8f43kq" (Async.RunSynchronously (async { let x = 1 in return x })) 1

    check "32o8f43kw" (try Async.RunSynchronously (async {  let x = failwith "error" in return x+1 }) with _ -> 2) 2

    check "32o8f43kr" (try Async.RunSynchronously (async {  let x = failwith "error" 
                                                            return x+1 }) with _ -> 2) 2

    //check "32o8f43kt" (Async.RunSynchronously (Async.Catch (async {  do failwith "error" }))) (Choice2Of2 (Failure "error"))
    check "32o8f43kta" (Async.RunSynchronously (Async.Catch (async {  return 1 }))) (Choice1Of2 1)

    check "32o8f43ktb" (Async.RunSynchronously (async { try 
                                                            do failwith "error" 
                                                            return 3
                                                        with _ -> 
                                                            return 2 
                                                      })) 2

    check "32o8f43ktc" 
        (Async.RunSynchronously
             (async {  try 
                          do failwith "error" 
                          return 3
                       with Failure _ -> 
                          return 2 
                    })) 
        2

    check "32o8f43ktd" 
        (Async.RunSynchronously
            (async {  try 
                         try 
                            do failwith "error" 
                            return 3
                         with :? System.ArgumentNullException -> 
                            return 4 
                       with Failure _ -> 
                          return 2 
                    })) 
        2

    check "32o8f43kte" 
                      (let x = ref 0 
                       Async.RunSynchronously 
                           (async {  try 
                                        return ()
                                     finally 
                                        x := 10
                                  });
                       !x) 10

    check "32o8f43ktf" 
                      (let x = ref 0 
                       (try 
                           Async.RunSynchronously 
                               (async {  try 
                                            do failwith ""
                                         finally 
                                            x := 10
                                      })
                        with Failure _ -> ());
                       !x) 10


    check "32o8f43ktg" 
                      (let x = ref 0 
                       (try 
                           Async.RunSynchronously 
                               (async {  try 
                                           try 
                                              do failwith ""
                                           finally 
                                              x := !x + 1
                                         finally 
                                            x := !x + 1
                                      })
                        with Failure _ -> ());
                       !x) 2

    check "32o8f43kth" 
                      (let x = ref 0 
                       (try 
                           Async.RunSynchronously 
                               (async {  try 
                                           try 
                                              return ()
                                           finally 
                                              do failwith ""
                                              x := !x + 1
                                         finally 
                                            x := !x + 1
                                      })
                        with Failure _ -> ());
                       !x) 1

    check "32o8f43ky" (try Async.RunSynchronously
                             (async {  try 
                                         try 
                                           do failwith "error" 
                                           return 3
                                         with _ -> 
                                           do failwith "error" 
                                           return 4
                                       with _ -> 
                                         return 2 
                                    }) with _ -> 6) 2

    check "32o8f43ku" (try Async.RunSynchronously 
                               (async {  let x = failwith "error" 
                                         do! Async.Sleep(30) 
                                         return x+1 }) with _ -> 2) 2

    check "32o8f43ki" (let p = async {  let x = failwith "error" 
                                        return x+1 } 
                       try Async.RunSynchronously p with _ -> 2) 2
                       
#if GenEqBug                        
    check "32o8f43ko" (Async.RunSynchronously
                          (Async.Parallel [| async { let x = 10+10 in return x+x }; 
                                             async { let y = 20+20 in return y+y } |])) [| 40; 80 |]
#endif      
    check "46sdhksdjf" 
        begin
            for i in 1..1000 do
                begin
                    Async.TryCancelled (async { while true do do! Async.Sleep(10) }, fun _ -> failwith "fail!") |> Async.Start
                    Async.CancelDefaultToken()
                end
            true                    
        end
        true



module JoinTests = 
    let Join (a1: Async<'a>) (a2: Async<'b>) = async {
      let! task1 = a1 |> Async.StartChild
      let! task2 = a2 |> Async.StartChild
      
      let! res1 = task1
      let! res2 = task2 
      return (res1,res2) }

    let JoinNoFailTest() = 
        check "cvew0-9rn1" 
             (Async.RunSynchronously (Join (async { return 1 + 1 }) 
                                           (async { return 2 + 2 } ))) 
             (2,4)
        check "cvew0-9rn2" 
             (Async.RunSynchronously (Join (async { do! Async.Sleep(30) 
                                                    return 1 + 1 }) 
                                           (async { do! Async.Sleep(30) 
                                                    return 2 + 2 } ))) 
             (2,4)

    let JoinFirstFailTest() = 
        check "cvew0-9rn3" 
             (try 
                 Async.RunSynchronously (Join (async { do! Async.Sleep(30) 
                                                       failwith "fail"
                                                       return 3+3 }) 
                                              (async { do! Async.Sleep(30) 
                                                       return 2 + 2 } ))
              with _ -> 
                 (0,0))                                               
             (0,0)

    let JoinSecondFailTest() = 
        check "cvew0-9rn4" 
             (try 
                 Async.RunSynchronously (Join (async { do! Async.Sleep(30) 
                                                       return 3+3 }) 
                                              (async { do! Async.Sleep(30) 
                                                       failwith "fail"
                                                       return 2 + 2 } ))
              with _ -> 
                 (0,0))                                               
             (0,0)


    let JoinBothFailTest() = 
        check "cvew0-9rn5d" 
             (try 
                 Async.RunSynchronously (Join (async { do! Async.Sleep(30) 
                                                       failwith "fail"
                                                       return 3+3 }) 
                                              (async { do! Async.Sleep(30) 
                                                       failwith "fail"
                                                       return 2 + 2 } ))
              with _ -> 
                 (0,0))                                               
             (0,0)

    JoinNoFailTest()
    JoinFirstFailTest()
    JoinSecondFailTest()
    JoinBothFailTest()
#if GenEqBug
module StartChildWaitMultipleTimes =
    let a = async {
                let! a = Async.StartChild(
                            async { 
                                do! Async.Sleep(500) 
                                return 27 
                            })
                let! result  = Async.Parallel [ a; a; a; a ]
                return result
            }
    check "dfhdu34y734"
        (a |> Async.RunSynchronously)
        [| 27; 27; 27; 27 |]
#endif
module StartChildTrampoliningCheck =
    let a = async {
                let! a = Async.StartChild(
                            async { 
                                do! Async.Sleep(500) 
                                return 27 
                            })
                let! result = a
                let x = ref result
                for i in 1..biggerThanTrampoliningLimit do
                    x := !x + 1
                return !x
            }
    check "ft6we56sgfw"
        (a |> Async.RunSynchronously)
        (biggerThanTrampoliningLimit+27)


module StartChildOutsideOfAsync =
  open System.Threading
  let Run() =

    check "dshfukeryhu8we"
        (let b = async {return 27} |> Async.StartChild
        (b |> Async.RunSynchronously |> Async.RunSynchronously)
        )
        27

    check "gf6dhasdfmkerio57: StartChild cancellation"
        begin
            use ev0 = new ManualResetEvent(false)
            use ev = new ManualResetEvent(false)
            let cts = new CancellationTokenSource()
            let child = async {
                            try
                                ev0.Set() |> ignore
                                while true do
                                    ()
                            finally 
                                ev.Set() |> ignore
                        } |> Async.StartChild
            Async.RunSynchronously(child,cancellationToken=cts.Token) |> ignore
            ev0.WaitOne() |> ignore// wait until cancellation handler is set
            cts.Cancel()
            ev.WaitOne(5000)
        end
        true
   

module SpawnTests = 
   let Run() = 
    check "32o8f43kaI: Spawn" 
        (let result = ref 0
         Async.Start(async { do printfn "hello 1"
                             do! Async.Sleep(30) 
                             do result := 1 });
         while !result = 0 do 
             printf "."
#if NetCore
             Task.Delay(10).Wait()
#else
             System.Threading.Thread.Sleep(10)
#endif
         !result) 1


module FromBeginEndTests = 
    // FromBeginEnd 
    let FromBeginEndTest() = 
        for completeSynchronously in [true;false] do
         for sleep in [0;50;100] do
          for expectedResult in [300;600] do
           for useCancelAction in [true;false] do
            for argCount in [0;1;2;3] do
                let name = sprintf "cvew0-9rn5a, completeSynchronously = %A, sleep = %A, expectedResult = %A,useCancelAction = %A, argCount = %A" completeSynchronously sleep expectedResult useCancelAction argCount
                printfn "running %s" name
                check 
                     name
                     (try 
                         Async.RunSynchronously 
                             (async { let completed = ref completeSynchronously
                                      let result = ref 0
                                      let ev = new System.Threading.ManualResetEvent(completeSynchronously)
                                      let iar = 
                                          { new System.IAsyncResult with
                                                member x.IsCompleted = !completed
                                                member x.CompletedSynchronously = completeSynchronously
                                                member x.AsyncWaitHandle = ev :> System.Threading.WaitHandle
                                                member x.AsyncState = null }
                                      let savedCallback = ref (None : System.AsyncCallback option)
                                      let complete(r) = 
                                          result := r
                                          if completeSynchronously then 
                                              completed := true 
                                              if (!savedCallback).IsNone then failwith "expected a callback (loc cwowen903)"
                                              (!savedCallback).Value.Invoke iar
                                          else 
#if NetCore
                                              Task.Run(fun _ -> 
                                                   Task.Delay(sleep).Wait()
#else
                                              System.Threading.ThreadPool.QueueUserWorkItem(fun _ -> 
                                                   System.Threading.Thread.Sleep sleep
#endif
                                                   completed := true 
                                                   ev.Set() |> ignore
                                                   if (!savedCallback).IsNone then failwith "expected a callback (loc cwowen903)"
                                                   (!savedCallback).Value.Invoke iar) |> ignore
                                      let beginAction0(callback:System.AsyncCallback,state) = 
                                          savedCallback := Some callback
                                          complete(expectedResult)
                                          iar
                                      let beginAction1(x:int,callback:System.AsyncCallback,state) = 
                                          savedCallback := Some callback
                                          complete(expectedResult+x)
                                          iar
                                      let beginAction2(x1:int,x2:int,callback:System.AsyncCallback,state) = 
                                          savedCallback := Some callback
                                          complete(expectedResult+x1+x2)
                                          iar
                                      let beginAction3(x1:int,x2:int,x3:int,callback:System.AsyncCallback,state) = 
                                          savedCallback := Some callback
                                          complete(expectedResult+x1+x2+x3)
                                          iar
                                      let endAction(iar:System.IAsyncResult) = !result
                                      let cancelAction = 
                                          if useCancelAction then 
                                              Some(fun () ->  complete(expectedResult))
                                          else
                                              None
                                          
                                      let! res = 
                                         match argCount with 
                                         | 0 -> Async.FromBeginEnd(beginAction0,endAction,?cancelAction=cancelAction)
                                         | 1 -> Async.FromBeginEnd(0,beginAction1,endAction,?cancelAction=cancelAction)
                                         | 2 -> Async.FromBeginEnd(7,-7,beginAction2,endAction,?cancelAction=cancelAction)
                                         | 3 -> Async.FromBeginEnd(7,-3,-4,beginAction3,endAction,?cancelAction=cancelAction)
                                         | _ -> failwith "bad argCount"
                                      return res })
                      with _ -> 
                         4)                                               
                     expectedResult

    FromBeginEndTest()

module Bug6078 =
    open System
    
    let Test() =
        let beginAction, endAction, _ =  Async.AsBeginEnd(fun () -> Async.Sleep(500))
        let sleepingAsync = Async.FromBeginEnd((fun (a,b) -> beginAction((),a,b)),endAction)
        let throwingAsync = async { raise <| new InvalidOperationException("foo") }
        
        for i in 1..100 do
            check "5678w6r78w" 
                begin
                    try
                        [   for j in 1..i do yield sleepingAsync; 
                            yield throwingAsync;
                            for j in i..1000 do yield sleepingAsync; ] |> Async.Parallel |> Async.RunSynchronously |> ignore
                        "weird"
                    with
                    |    :? InvalidOperationException as e -> e.Message
                end
                "foo"
    Test()

module AwaitEventTests = 
    let AwaitEventTest() = 
        // AwaitEvent
        for completeSynchronously in [ (* true; *) false] do
         for sleep in [0;50;100] do
          for expectedResult in [300;600] do
           for useCancelAction in [true;false] do
                let name = sprintf "cvew0-9rn5b, completeSynchronously = %A, sleep = %A, expectedResult = %A,useCancelAction = %A" completeSynchronously sleep expectedResult useCancelAction 
                printfn "running %s" name
                
                check 
                     name
                     (try 
                         Async.RunSynchronously 
                             (async { let ev = new Event<_>()
                                      let over = ref false
                                      let complete(r) = 
                                          if completeSynchronously then 
                                              ev.Trigger(r)
                                          else 
#if NetCore
                                              Task.Run(fun _ -> 
                                                   Task.Delay(sleep).Wait()
#else
                                              System.Threading.ThreadPool.QueueUserWorkItem(fun _ -> 
                                                   System.Threading.Thread.Sleep sleep
#endif
                                                   ev.Trigger(r)) |> ignore
                                      
                                      let cancelAction = 
                                          if useCancelAction then 
                                              Some(fun () ->  ev.Trigger(expectedResult))
                                          else
                                              None
                                      // The completion must come after the event is triggerd
                                      let! child = 
                                           async { do! Async.Sleep 200;  // THIS TIME MUST BE LONG ENOUGH FOR THE EVENT HANDLER TO WIRE UP
                                                   complete(expectedResult)   }
                                           |> Async.StartChild
                                      let! res = Async.AwaitEvent(ev.Publish)
                                      for i in 1..biggerThanTrampoliningLimit do ()
                                      over := true 
                                      return res })
                      with e -> 
                         printfn "ERROR: %A" e
                         4)                                               
                     expectedResult


    //AwaitEventTest()


module AsBeginEndTests = 

    type AsyncRequest<'T>(p:Async<'T>) = 
        
        let beginAction,endAction,cancelAction = Async.AsBeginEnd (fun () -> p)
        member this.BeginAsync(callback,state:obj) = 
            beginAction((),callback,state)

        member this.EndAsync(iar: System.IAsyncResult)  = endAction(iar)

        member this.CancelAsync(iar)           = cancelAction(iar)
        
    type AsyncRequest1<'T>(p:int -> Async<'T>) = 
        
        let beginAction,endAction,cancelAction = Async.AsBeginEnd p
        member this.BeginAsync(arg1,callback,state:obj) = 
            beginAction(arg1,callback,state)

        member this.EndAsync(iar)  = endAction(iar)

        member this.CancelAsync(iar)           = cancelAction(iar)

    type AsyncRequest2<'T>(p:int -> string -> Async<'T>) = 
        
        let beginAction,endAction,cancelAction = Async.AsBeginEnd (fun (arg1,arg2) -> p arg1 arg2)
        member this.BeginAsync(arg1,arg2,callback,state:obj) = beginAction((arg1,arg2),callback,state)

        member this.EndAsync(iar)  = endAction(iar)

        member this.CancelAsync(iar)           = cancelAction(iar)

    type AsyncRequest3<'T>(p:int -> string -> int -> Async<'T>) = 
        
        let beginAction,endAction,cancelAction = Async.AsBeginEnd (fun (arg1,arg2,arg3) -> p arg1 arg2 arg3)
        member this.BeginAsync(arg1,arg2,arg3,callback,state:obj) = 
            beginAction((arg1,arg2,arg3),callback,state)

        member this.EndAsync(iar: System.IAsyncResult)  = 
            endAction(iar)

        member this.CancelAsync(iar)           = cancelAction(iar)




    let AsBeginEndTest() = 
        check
           (sprintf "cvew0-9rn1")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,null)
            iar.CompletedSynchronously)
           true


        check
           (sprintf "cvew0-9rn2")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,null)
            iar.IsCompleted)
           true

        check
           (sprintf "cvew0-9rn2-state")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,box 1)
            iar.AsyncState |> unbox<int>)
           1

        check
           (sprintf "cvew0-9rn3")
           (let req = AsyncRequest( async { do! Async.Sleep 100 } ) 
            let iar = req.BeginAsync(null,null)
            iar.IsCompleted)
           false

        check
           (sprintf "cvew0-9rn3-state")
           (let req = AsyncRequest( async { do! Async.Sleep 100 } ) 
            let iar = req.BeginAsync(null,box 1)
            iar.AsyncState |> unbox<int>)
           1

        check
           (sprintf "cvew0-9rn4")
           (let req = AsyncRequest( async { do! Async.Sleep 100 } ) 
            let iar = req.BeginAsync(null,null)
            iar.CompletedSynchronously)
           false

        check
           (sprintf "cvew0-9rn5c")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,null)
            req.EndAsync(iar))
           2087

        check
           (sprintf "cvew0-9rn5c-1")
           (let req = AsyncRequest1( fun i -> async { return i } ) 
            let iar = req.BeginAsync(2087, null,null)
            req.EndAsync(iar))
           2087

        check
           (sprintf "cvew0-9rn5c-1-state")
           (let req = AsyncRequest1( fun i -> async { return i } ) 
            let iar = req.BeginAsync(2087, null,box 1)
            iar.AsyncState |> unbox<int>)
           1

        check
           (sprintf "cvew0-9rn5c-2")
           (let req = AsyncRequest2( fun i j -> async { return i + int j } ) 
            let iar = req.BeginAsync(2087, "1", null,null)
            req.EndAsync(iar))
           2088


        check
           (sprintf "cvew0-9rn5c-2-state")
           (let req = AsyncRequest2( fun i j -> async { return i + int j } ) 
            let iar = req.BeginAsync(2087, "1", null,box 10)
            iar.AsyncState |> unbox<int>)
           10

        check
           (sprintf "cvew0-9rn5c-3")
           (let req = AsyncRequest3( fun i j k -> async { return i + int j + k} ) 
            let iar = req.BeginAsync(2087, "1", 2, null,null)
            req.EndAsync(iar))
           2090


        check
           (sprintf "cvew0-9rn5c-3-state")
           (let req = AsyncRequest3( fun i j k -> async { return i + int j + k} ) 
            let iar = req.BeginAsync(2087, "1", 17, null,box "10")
            iar.AsyncState |> unbox<string>)
           "10"

        check
           (sprintf "cvew0-9rn6")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,null)
            req.EndAsync(iar) |> ignore
            try req.EndAsync(iar) with :? System.ObjectDisposedException -> 100)
           100

        check
           (sprintf "cvew0-9rn7")
           (let req = AsyncRequest( async { return 2087 } ) 
            let iar = req.BeginAsync(null,null)
            iar.AsyncWaitHandle.WaitOne(100,true) |> ignore
            req.EndAsync(iar))
           2087

        check
           (sprintf "cvew0-9rn8")
           (let req = AsyncRequest( async { return 2087 } ) 
            let called = ref 0
            let iar = req.BeginAsync(System.AsyncCallback(fun _ -> called := 10),null)
            iar.AsyncWaitHandle.WaitOne(100,true) |> ignore
            let v = req.EndAsync(iar)
            v + !called)
           2097

        check
           (sprintf "cvew0-9rn9")
           (let req = AsyncRequest( async { return 2087 } ) 
            let called = ref 0
            let iar = req.BeginAsync(System.AsyncCallback(fun iar -> called := req.EndAsync(iar)),null)
            while not iar.IsCompleted do
                 iar.AsyncWaitHandle.WaitOne(100,true) |> ignore
            
            !called)
           2087



        check
           (sprintf "cvew0-9rnA")
           (let req = AsyncRequest( async { do! Async.SwitchToNewThread()
                                            while true do 
                                                do! Async.Sleep 10 
                                            return 10 } ) 
            let iar = req.BeginAsync(null,null)
            printfn "waiting"
            iar.AsyncWaitHandle.WaitOne(100,true) |> ignore
            printfn "cancelling"
            req.CancelAsync(iar)
            (try req.EndAsync(iar) with :? System.OperationCanceledException as e -> 100 ))
           100

    //AsBeginEndTest()

(*

check "32o8f43kaO: Cancel a While loop" 
    (let count = ref 0
     let res = ref 0
     let asyncGroup = new new System.Threading.CancellationTokenSource()
     Async.Spawn(async { do! async { use! holder = Async.OnCancel (fun msg -> printfn "got cancellation...."; incr res) 
                                     while true do
                                         do! Async.Sleep(10) 
                                         do printfn "in loop..."
                                         do count := !count + 1 
                                     do printfn "exited loop..." } 
                         do printfn "exited use!..." },
                 asyncGroup=asyncGroup);
     while !count = 0 do 
         do printfn "waiting to enter loop..."
         Async.Sleep(10)
     
     asyncGroup.TriggerCancel "cancel"
     while !res= 0 do 
         do printfn "32o8f43kaP: waiting to for cancellation...."
         Async.Sleep(10)
     !res) 1


check "32o8f43ka2: Cancel a For loop" 
    (let count = ref 0
     let res = ref 0
     let asyncGroup = new new System.Threading.CancellationTokenSource()
     Async.Spawn(async { do! async { use! holder = Async.OnCancel (fun msg -> printfn "got cancellation...."; incr res) 
                                     for x in Seq.initInfinite (fun i -> i) do
                                         do! Async.Sleep(10) 
                                         do printfn "in loop..."
                                         do count := !count + 1 
                                     do printfn "exited loop without cancellation!" }
                         do printfn "exited use without cancellation!" },
                 asyncGroup=asyncGroup);
     while !count = 0 do 
         do printfn "waiting to enter loop..."
         Async.Sleep(10)
     
     asyncGroup.TriggerCancel "cancel"
     while !res= 0 do 
         do printfn "32o8f43ka2: waiting to for cancellation...."
         Async.Sleep(10)
     !res) 1
*)

module OnCancelTests = 
  let Run() = 
    check "32o8f43ka1: No cancellation" 
        (let count = ref 0
         let res = ref 0
         let asyncGroup = new System.Threading.CancellationTokenSource ()
         Async.Start(async { use! holder = Async.OnCancel (fun msg -> printfn "got cancellation...."; incr res) 
                             do incr count
                             return () }, asyncGroup.Token);
         while !count = 0 do 
             do printfn "waiting to enter cancellation section"
#if NetCore
             Task.Delay(10).Wait()
#else
             System.Threading.Thread.Sleep(10)
#endif
        
         !res) 0


#if Portable
#else
module SyncContextReturnTests = 

    let p() = printfn "running on %A" System.Threading.SynchronizationContext.Current

    let run p = Async.RunSynchronously p


    let rec fakeCtxt = { new System.Threading.SynchronizationContext() with 
                             member x.Post(work,state) = 
                                 //printfn "Posting..."


                                 System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback(fun _ -> 
                                     //printfn "Setting..."
                                     System.Threading.SynchronizationContext.SetSynchronizationContext fakeCtxt
                                     work.Invoke(state))) |> ignore }

    let checkOn s expectedCtxt = 
        check s System.Threading.SynchronizationContext.Current expectedCtxt

    let setFakeContext() = 
        async { do! Async.SwitchToNewThread()
                let ctxt = System.Threading.SynchronizationContext.Current 
                System.Threading.SynchronizationContext.SetSynchronizationContext fakeCtxt
                return { new System.IDisposable with 
                             member x.Dispose() = 
                                 printfn "Disposing..."
                                 // Set the synchronization context back to its original value
                                 System.Threading.SynchronizationContext.SetSynchronizationContext ctxt }  }
            
    // CHeck that Async.Sleep returns to the sync context
    async { use! holder = setFakeContext()
            p()
            checkOn "evrher921" fakeCtxt
            p()
            do! Async.Sleep 100
            p()
            checkOn "evrher962" fakeCtxt }
       |> run

    // CHeck that Async.AwaitWaitHandle returns to the sync context
    async { use! holder = setFakeContext()
            checkOn "evrher923" fakeCtxt
            p()
            let wh = new System.Threading.ManualResetEvent(true)
            p()
            let! ok = Async.AwaitWaitHandle(wh,0)
            p()
            checkOn "evrher964" fakeCtxt }
       |> run

    // CHeck that Async.AwaitWaitHandle returns to the sync context
    async { use! holder = setFakeContext()
            checkOn "evrher925" fakeCtxt
            p()
            let wh = new System.Threading.ManualResetEvent(true)
            p()
            let! ok = Async.AwaitWaitHandle(wh,-1)
            p()
            checkOn "evrher966" fakeCtxt }
       |> run

    // CHeck that Async.AwaitWaitHandle returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [-1; 0; 100] do
                checkOn "evrher927" fakeCtxt
                p()
                let wh = new System.Threading.ManualResetEvent(true)
                p()
                let! ok = Async.AwaitWaitHandle(wh,timeout)
                p()
                checkOn "evrher968" fakeCtxt }
       |> run

    // CHeck that Async.AwaitWaitHandle returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [100] do
                checkOn "evrher927" fakeCtxt
                p()
                let wh = new System.Threading.ManualResetEvent(false)
                p()
                // this will timeout
                let! ok = Async.AwaitWaitHandle(wh,timeout)
                p()
                checkOn "evrher968" fakeCtxt }
       |> run


    // CHeck that Async.AwaitWaitHandle returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [1;10] do
                checkOn "evrher929" fakeCtxt
                let wh = new System.Threading.ManualResetEvent(false)
                let! ok = Async.AwaitWaitHandle(wh,timeout)
                checkOn "evrher96Q" fakeCtxt }
       |> run

    // CHeck that Async.AwaitEvent returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [1;10] do
                checkOn "evrher92W" fakeCtxt
                let ev = new Event<int>()
                // Trigger the event in 400ms
                async { do! Async.Sleep 400
                        ev.Trigger 10 } |> Async.Start

                let! args = Async.AwaitEvent(ev.Publish)
                checkOn "evrher96E" fakeCtxt }
       |> run


    // CHeck that Async.FromBeginEnd returns to the sync context
    async { use! holder = setFakeContext()
            for completeSynchronously in [true;false] do
             for sleep in [0;50;100] do
              for expectedResult in [300;600] do
               for useCancelAction in [true;false] do
                for argCount in [0;1;2;3] do
                    let name = sprintf "vwwegbwerben5a, completeSynchronously = %A, sleep = %A, expectedResult = %A,useCancelAction = %A, argCount = %A" completeSynchronously sleep expectedResult useCancelAction argCount
                    printfn "running %s" name
                    
                    // THIS IS ONE CHECK
                    checkOn name fakeCtxt
                    
                    let completed = ref completeSynchronously
                    let result = ref 0
                    let ev = new System.Threading.ManualResetEvent(completeSynchronously)
                    let iar = 
                        { new System.IAsyncResult with
                              member x.IsCompleted = !completed
                              member x.CompletedSynchronously = completeSynchronously
                              member x.AsyncWaitHandle = ev :> System.Threading.WaitHandle
                              member x.AsyncState = null }
                    let savedCallback = ref (None : System.AsyncCallback option)
                    let complete(r) = 
                        result := r
                        if completeSynchronously then 
                            completed := true 
                            if (!savedCallback).IsNone then failwith "expected a callback (loc cwowen903)"
                            (!savedCallback).Value.Invoke iar
                        else 
                            System.Threading.ThreadPool.QueueUserWorkItem(fun _ -> 
                                 System.Threading.Thread.Sleep sleep
                                 completed := true 
                                 ev.Set() |> ignore
                                 if (!savedCallback).IsNone then failwith "expected a callback (loc cwowen903)"
                                 (!savedCallback).Value.Invoke iar) |> ignore
                    let beginAction0(callback:System.AsyncCallback,state) = 
                        savedCallback := Some callback
                        complete(expectedResult)
                        iar
                    let beginAction1(x:int,callback:System.AsyncCallback,state) = 
                        savedCallback := Some callback
                        complete(expectedResult+x)
                        iar
                    let beginAction2(x1:int,x2:int,callback:System.AsyncCallback,state) = 
                        savedCallback := Some callback
                        complete(expectedResult+x1+x2)
                        iar
                    let beginAction3(x1:int,x2:int,x3:int,callback:System.AsyncCallback,state) = 
                        savedCallback := Some callback
                        complete(expectedResult+x1+x2+x3)
                        iar
                    let endAction(iar:System.IAsyncResult) = !result
                    let cancelAction = 
                        if useCancelAction then 
                            Some(fun () ->  complete(expectedResult))
                        else
                            None

                    // THIS IS ONE CHECK
                    checkOn name fakeCtxt
                    
                        
                    let! res = 
                       match argCount with 
                       | 0 -> Async.FromBeginEnd(beginAction0,endAction,?cancelAction=cancelAction)
                       | 1 -> Async.FromBeginEnd(0,beginAction1,endAction,?cancelAction=cancelAction)
                       | 2 -> Async.FromBeginEnd(7,-7,beginAction2,endAction,?cancelAction=cancelAction)
                       | 3 -> Async.FromBeginEnd(7,-3,-4,beginAction3,endAction,?cancelAction=cancelAction)
                       | _ -> failwith "bad argCount"

                    // THIS IS ONE CHECK
                    checkOn name fakeCtxt }
       |> run

    // CHeck that Async.Parallel returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [1;10] do
                checkOn "evrher92R" fakeCtxt
                let ev = new Event<int>()

                let! args = Async.Parallel [ for i in 0 .. 10 -> async { return i * 2 } ]
                checkOn "evrher96T" fakeCtxt }
       |> run


    // CHeck that Async.Parallel returns to the sync context
    async { use! holder = setFakeContext()
            for timeout in [1;10] do
                checkOn "evrher92R" fakeCtxt
                let ev = new Event<int>()

                try 
                   let! args = Async.Parallel [ for i in 0 .. 10 -> async { failwith "" } ]
                   checkOn "evrher96T" fakeCtxt
                   return ()
                with _ -> 
                   checkOn "evrher96T" fakeCtxt }
       |> run
#endif
#if GenEqBug
module GenerateTests = 
  let Run() = 
    for n = 0 to 20 do
        check (sprintf "32o8f43ka2: Async.Generate, n = %d" n)
            (Async.RunSynchronously (Async.Generate(n, (fun i -> async { return i })))) [| 0..n-1 |]
        
    for n = 0 to 20 do
        check (sprintf "32o8f43ka3: Async.Generate w/- Sleep, n = %d" n) 
            (Async.RunSynchronously (Async.Generate(n, (fun i -> async { do! Async.Sleep(1) 
                                                                         return i })))) [| 0..n-1 |]

    for n = 1 to 20 do
        check 
            (sprintf "32o8f43ka4: Async.Generate w/- last failure, n = %d" n)
            (try Async.RunSynchronously (Async.Generate(n, (fun i -> async { if i=n-1 then return failwith "last failure" else return i }))) 
             with Failure "last failure" -> [| 0xdeadbeef |])
            [| 0xdeadbeef |]

    for n = 1 to 20 do
        check 
            (sprintf "32o8f43ka5: Async.Generate w/- all failure, n = %d" n)
            (try Async.RunSynchronously (Async.Generate(n, (fun i -> async { return failwith "failure" }))) 
             with Failure "failure" -> [| 0xdeadbeef |])
            [| 0xdeadbeef |]
#endif
module ParallelTests = 
  let Run() = 
#if GenEqBug
    for n = 1 to 20 do
        check 
            (sprintf "32o8f43ka6: Async.Parallel w/- last failure, n = %d" n)
            (try Async.RunSynchronously (Async.Parallel [ for i in 0 .. n-1 -> async { if i=n-1 then return failwith "last failure" else return i }]) 
             with Failure "last failure" -> [| 0xdeadbeef |])
            [| 0xdeadbeef |]


    for n = 1 to 20 do
        check 
            (sprintf "32o8f43ka7: Async.Parallel w/- last failure and Sleep, n = %d" n)
            (try Async.RunSynchronously (Async.Parallel [ for i in 0 .. n-1 -> async { do! Async.Sleep(1) 
                                                                                       if i=n-1 then return failwith "last failure" else return i }]) 
             with Failure "last failure" -> [| 0xdeadbeef |])
            [| 0xdeadbeef |]

    // This test checks that sub-processes are successfully cancelled
    for n = 1 to 20 do
        check 
            (sprintf "32o8f43ka8: Async.Parallel w/- last failure and force cancellation, n = %d" n)
            (try Async.RunSynchronously 
                     (Async.Parallel 
                         [ for i in 0 .. n-1 -> 
                            async { // The last process is the one that causes the failure. 
                                    do! Async.Sleep(1) 
                                    if i=n-1 then 
                                      return failwith "last failure" 
                                    else 
                                      // All the other processes just loop until they are cancelled
                                      // Note - this doesn't return - it must be cancelled
                                      while true do 
                                        do! Async.Sleep(1) 
                                      return 1 }]) 
             with Failure "last failure" -> [| 0xabbaabba |])
            // the expected result
            [| 0xabbaabba |]

    // This test checks that sub-processes are successfully cancelled, AND that we wait for all processes
    // to be cancelled and finish before we return the overall result
    for n = 2 to 20 do
        check 
            (sprintf "32o8f43ka9: Async.Parallel w/- last failure and cancellation with check that cleanup occurs, n = %d" n)
            (let cleanedUp = ref false
             try Async.RunSynchronously 
                    (Async.Parallel 
                        [ for i in 0 .. n-1 -> 
                            async { // The last process is the one that causes the failure. It waits 50ms to allow
                                    // at least one of the other processes to commence and enter its "use" region
                                    if i=n-1 then 
                                         do! Async.Sleep(50) 
                                         return failwith "last failure" 
                                    else
                                        // All the other processes just loop until they are cancelled
                                        // They record the fact that they were cancelled in a try/finally
                                        // compensation handler (via a 'use'). 
                                        //
                                        use r = { new System.IDisposable with 
                                                    member x.Dispose() = 
                                                       // This gets run when the cancel happens
                                                       // Sleep a bit to check we wait for the sleep after the cancel
#if NetCore
                                                       Task.Delay(10).Wait()
#else
                                                       System.Threading.Thread.Sleep(10)
#endif
                                                       cleanedUp := true } 
                                        // Note - this doesn't return - it must be cancelled
                                        while true do 
                                            do! Async.Sleep(1) 
                                        return 1 }]) 
             with Failure "last failure" -> [| (if !cleanedUp then 0xabbaabba else 0xdeaddead) |])
            // the expected result
            [| 0xabbaabba |]

    for n = 1 to 20 do
        check 
            (sprintf "32o8f43kaQ: Async.Parallel w/- all failure, n = %d" n)
            (try Async.RunSynchronously (Async.Parallel [ for i in 0 .. n-1 -> async { return failwith "failure" }]) 
             with Failure "failure" -> [| 0xdeadbeef |])
            [| 0xdeadbeef |]
            
    for n = 0 to 20 do
        check (sprintf "32o8f43kaW: Async.Parallel, n = %d" n) 
            (Async.RunSynchronously (Async.Parallel( [ for i in 0 .. n-1 -> async { return i } ]))) [| 0..n-1 |]
        
    for n = 0 to 20 do
        check (sprintf "32o8f43kaE: Async.Parallel with Sleep, n = %d" n) 
            (Async.RunSynchronously (Async.Parallel( [ for i in 0 .. n-1 -> async { do! Async.Sleep(1) 
                                                                                    return i } ]))) [| 0..n-1 |]
#endif        
    check "328onic4: Async.Parallel2" (Async.RunSynchronously (Async.Parallel2(async { return 1 }, async { return 2 }))) (1,2)
    check "328onic4: Async.Parallel3" (Async.RunSynchronously (Async.Parallel3(async { return 1 }, async { return 2 }, async { return 3 }))) (1,2,3)
#if GenEqBug
    for n = 0 to 20 do
        check (sprintf "32o8f43kaR: Async.Parallel with SwitchToNewThread, n = %d" n) 
            (Async.RunSynchronously 
                (Async.Parallel( [ for i in 0 .. n-1 -> async { do! Async.SwitchToNewThread()
                                                                return i } ]))) [| 0..n-1 |]
        
    for n = 0 to 20 do
        check (sprintf "32o8f43kaT: Async.Parallel with SwitchToThreadPool, n = %d" n) 
            (Async.RunSynchronously
                (Async.Parallel( [ for i in 0 .. n-1 -> async { do! Async.SwitchToThreadPool()
                                                                return i } ]))) [| 0..n-1 |]
 
    for n = 0 to 20 do
        check 
            (sprintf "32o8f43kaY: Async.Parallel with FromContinuations, n = %d" n) 
            (Async.RunSynchronously (Async.Parallel( [ for i in 0 .. n-1 -> Async.FromContinuations(fun (cont,econt,ccont) -> cont i) ])))
            [| 0..n-1 |]
#endif

#if NetCore
#else
module AsyncWaitOneTest1 = 
  let Run() = 
        
    check 
        "c32398u1: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(true)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) })) 
        true

    check 
        "c32398u2: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(true)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) })) 
        true

    check 
        "c32398u3: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(false)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) })) 
        false // we never set the event, so the result is false
        
    check 
        "c32398u4: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(false)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = 10) })) 
        false // we never set the event, so the result is false

    check 
        "c32398u5: AsyncWaitOne"
        (let wh = new System.Threading.AutoResetEvent(true)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) })) 
        true

    check 
        "c32398u6: AsyncWaitOne"
        (let wh = new System.Threading.AutoResetEvent(true)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = 10) })) 
        true

    check 
        "c32398u7: AsyncWaitOne"
        (let wh = new System.Threading.AutoResetEvent(true)
         Async.RunSynchronously (async { return! Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) })) 
        true

    check 
        "c32398u8: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(true)
         Async.RunSynchronously
             (async { let! ok1 = Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) 
                      // check the event is still set (it's a ManualResetEvent)
                      let! ok2 = Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) 
                      return ok1 && ok2 })) 
        true

    check 
        "c32398u9: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(false)
         Async.RunSynchronously 
             (async { let! _ = Async.StartChild (async { 
                                                        System.Threading.Thread.Sleep(100)
                                                        let _ = wh.Set() in () })
                      let! ok1 = Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) 
                      // check the event is still set (it's a ManualResetEvent)
                      let! ok2 = Async.AwaitWaitHandle(wh,millisecondsTimeout = -1) 
                      return ok1 && ok2 })) 
        true

    check 
        "c32398u10: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(false)
         Async.RunSynchronously 
             (async { let! _ = Async.StartChild (async { let _ = wh.Set() in () })
                      // 1000 milliseconds should be enough to get the result
                      let! ok1 = Async.AwaitWaitHandle(wh,millisecondsTimeout = 1000) 
                      // check the event is still set (it's a ManualResetEvent)
                      let! ok2 = Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) 
                      return ok1 && ok2 })) 
        true

    check 
        "c32398u11: AsyncWaitOne"
        (let wh = new System.Threading.ManualResetEvent(false)
         Async.RunSynchronously 
             (async { let! _ = Async.StartChild (async {  System.Threading.Thread.Sleep(100); let _ = wh.Set() in () })
                      // no timeout = infinite
                      let! ok1 = Async.AwaitWaitHandle(wh) 
                      // check the event is still set (it's a ManualResetEvent)
                      let! ok2 = Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) 
                      return ok1 && ok2 })) 
        true

    check 
        "c32398u12: AsyncWaitOne"
        (let wh = new System.Threading.AutoResetEvent(false)
         Async.RunSynchronously 
             (async { let! _ = Async.StartChild (async {  System.Threading.Thread.Sleep(100); let _ = wh.Set() in () })
                      // no timeout = infinite
                      let! ok1 = Async.AwaitWaitHandle(wh) 
                      // check the event is not still set (it's an AutoResetEvent)
                      let! ok2 = Async.AwaitWaitHandle(wh,millisecondsTimeout = 0) 
                      return ok1 && not ok2 })) 
        true

(*
let s = new System.IO.MemoryStream(1000)
let buffer = Array.create<byte> 1000 32uy

s.Read(buffer,0,10)
Async.RunSynchronously (async { let! n = s.AsyncRead(buffer,0,10) in return n })

s.Write(buffer,0,10)
Async.RunSynchronously (async { let! n = s.AsyncRead(buffer,0,10) in return n })
s.Length
s.ReadByte()
s.CanRead
s.CanWrite
s.GetBuffer()
s.Seek(0L,System.IO.SeekOrigin.Begin)
Async.RunSynchronously (async { let! n = s.AsyncRead(buffer,0,9) in return n }) = 9
Async.RunSynchronously (async { let! n = s.AsyncRead(buffer,0,9) in return n }) = 1
*)
#endif

#if NetCore
#else
module AsyncGenerateTests = 
  let Run() = ()
#if GenEqBug
    for length in 1 .. 10 do
        for chunks in 1 .. 10 do 
            check (sprintf "c3239438u: Run/Generate, length=%d, chunks=%d" length chunks)
                (Async.RunSynchronously(Async.Generate(length, (fun i -> async {return i}), chunks)))
                [| 0 .. length-1|];;


    for length in 0 .. 10 do
        for chunks in 1 .. 10 do 
            check (sprintf "c3239438v: Run/Generate, length=%d, chunks=%d" length chunks)
                (try Async.RunSynchronously
                         (Async.Generate(length, (fun i -> async { do System.Threading.Thread.Sleep(chunks)
                                                                   return i}), chunks), timeout=length) 
                 with :? System.TimeoutException -> [| 0 .. length-1|])
                [| 0 .. length-1|];;

    for length in 1 .. 10 do
        for chunks in 1 .. 10 do 
            let action i : Async<int> = 
                async { 
                    do System.Threading.Thread.Sleep(chunks)
                    return i
                } 
            let a = async { 
                let! child = Async.Generate(length, action, chunks) |> Async.StartChild
                return! child
            } 
            check (sprintf "c3239438w: Run/StartChild/Generate, length=%d, chunks=%d" length chunks)
                (a |>Async.RunSynchronously)
                [| 0 .. length-1|];;


    for length in 0 .. 10 do
        for chunks in 1 .. 10 do 
            let action i : Async<int> = 
                async { 
                    do System.Threading.Thread.Sleep(chunks)
                    return i
                } 
            let a = 
                async { 
                    try
                      let! result = Async.StartChild(
                                                Async.Generate(length, action, chunks), 
                                                millisecondsTimeout=length)
                      return! result
                    with :? System.TimeoutException -> return [| 0 .. length-1|]
                }
            check (sprintf "c3239438x: Run/StartChild/Generate, length=%d, chunks=%d" length chunks)
                (a |>Async.RunSynchronously)
                [| 0 .. length-1|];;
#endif
#endif

#if NetCore
#else
(*
#This part of control suite disabled under bug#1809
module ThreadAbortTests = 
    open System.Threading

    for i = 1 to 100 do 
        let t = new Thread(new ThreadStart(fun _ -> 
            for j in 1 .. 10 do
                Async.RunSynchronously(async { 
                    for i in 1 .. 10 do
                        do printfn "running async ... j = %d, i = %d" j i
                        do Async.Sleep(10)
                    return () })), IsBackground=true)

        t.Start()
        Async.Sleep(1)
        t.Abort()


    open System.Threading

    type msg = Fetch of AsyncReplyChannel<int>

    let rec bp : MailboxProcessor<msg>
       = new MailboxProcessor<msg>(fun inbox -> 
                  let rec loop () = async { 
                      do printfn "receiving... #msg = %d" (Seq.length bp.UnsafeMessageQueueContents)

                      let! (Fetch msg) = inbox.Receive()   
                      do Async.Sleep(10)
                      
                      do msg.Post(3)
                      return! loop () }
                  loop())

    bp.Start()

    bp.UnsafeMessageQueueContents              
    for k = 1 to 100 do
        let t = new Thread(new ThreadStart(fun _ -> 
            for j in 1 .. 10 do
                printfn "res = %d" (bp.PostAndReply(fun reply -> Fetch(reply)))
            ), IsBackground=true)

        printfn "starting..." 
        t.Start()
        Async.Sleep(10)
        printfn "aborting..." 
        t.Abort()
*)
#endif

let time f x = 
    let timer = System.Diagnostics.Stopwatch.StartNew ()
    let res = f x
    res, timer.Elapsed

// some long computation...
let rec fibo = function
  | 0 | 1 -> 1
  | n -> fibo (n - 1) + fibo (n - 2)


let fail = async { do failwith "fail" }


let expect_failure a =
  async { try
            do! a
            return false
          with _ -> return true }

// Exception catching test
let test1 () =
    test "test1" (expect_failure fail |> Async.RunSynchronously)


let catch a =
    Async.RunSynchronously
        (async {try let! _ = a
                    return ()
                with _ -> return ()})

let to_be_cancelled n flag1 flag2 =
  async { use! holder = Async.OnCancel(fun _ -> incr flag1)
#if NetCore
          do Task.Delay(n/8).Wait()
#else
          do System.Threading.Thread.Sleep (n / 8)
#endif
          let! _ = async { return 1 } // implicit cancellation check
          do incr flag2}


// Cancellation test
let test2 () =
    let flag1 = ref 0
    let flag2 = ref 0
    let n = 400
    for i in 1 .. n / 2 do
       catch (Async.Parallel2(fail, to_be_cancelled i flag1 flag2))
       catch (Async.Parallel2(to_be_cancelled i flag1 flag2, fail))
    printfn "%d, %d" !flag1 !flag2
    test "test2 - OnCancel" (!flag1 >= 0 && !flag1 < n && !flag2 >= 0 && !flag2 < n)


#if NetCore
#else
// SwitchToNewThread
let test3 () =
    let ids = ref []
    let rec a n =
        async { do ids := System.Threading.Thread.CurrentThread.ManagedThreadId :: !ids
                do! Async.SwitchToNewThread()
                if n < 100 then 
                    do! a (n + 1) }
                    
    // on low-resouce test VMs, this might not pass on the first try.  Give a few chances.               
    let rec doTest maxAttempts =
        printfn "doTest, maxAttempts %d" maxAttempts
        match maxAttempts with
        | n when n <= 0 -> ()  // give up
        | _ ->
            ids := []
            Async.RunSynchronously (a 1)
            let res = (set !ids).Count
            if res > 1 then ()
            else 
               printfn "res = %d" res
               doTest (maxAttempts - 1)

    doTest 5
    let res = (set !ids).Count
    test (sprintf "test3 - SwitchToNewThread  res = %d" res) (res > 1)
#endif

(*
// Performance test (only if multi-core)
let test4 () =
    let fibo_1() =
        fibo 32 |> ignore;
        fibo 32 |> ignore;
        fibo 32 |> ignore;
        fibo 32

    // should be at least 20% faster if multi-core
    let fibo_2() =
        let a1 = Async.SpawnFuture(async { return fibo 32 })
        let a2 = Async.SpawnFuture(async { return fibo 32 })
        let a3 = Async.SpawnFuture(async { return fibo 32 })
        fibo 32 |> ignore
        a1.Value |> ignore
        a2.Value |> ignore
        a3.Value

    let (r1, t1), (r2, t2) = time fibo_1 (), time fibo_2 ()
    test "test4 - future (multi-core)" (r1 = r2)
    printfn "test4 - performance, ratio = %f, expect < 0.8" (float t2.Ticks / float t1.Ticks)
    if t2.Ticks > t1.Ticks * 80L / 100L then
        printfn "  Warning: performance test failed."

*)
#if GenEqBug
// test thread safety (using a lock)
let test8() =
    printfn "test8 started"
    let syncRoot = System.Object()
    let k = ref 0
    let comp _ = async { return lock syncRoot (fun () -> incr k
#if NetCore
                                                         Task.Delay(1).Wait()
#else
                                                         System.Threading.Thread.Sleep(1)
#endif
                                                         !k ) }
    let arr = Async.RunSynchronously (Async.Parallel(Seq.map comp [1..50]))
    test "test8 - lock" ((Array.sortWith compare arr) = [|1..50|])

// without lock, there "must" be concurrent problems
let test9() =
    let syncRoot = System.Object()
    let k = ref 0
    let comp _ = async { do incr k
                         do! Async.Sleep(10)
                         return !k }
    let arr = Async.RunSynchronously (Async.Parallel(Seq.map comp [1..100]))
    test "test9 - no lock" ((Array.sortWith compare arr) <> [|1..100|])
#endif
#if GenEqBug
// performance of Async.Parallel
let test10() =
    let fibo_1() =
        Array.init 37 fibo

    // should be at least 30% faster if multi-core
    let fibo_2() =
        let compute n = async { return fibo n }
        let arr = Array.init 37 compute
        Async.RunSynchronously (Async.Parallel arr)

    try
        let (r1, t1), (r2, t2) = time fibo_1 (), time fibo_2 ()
        test "test10 - Async.Parallel" (r1 = r2)
        printfn "test10 - performance, ratio = %f, expect < 0.8" (float t2.Ticks / float t1.Ticks)
        if t2.Ticks > t1.Ticks * 80L / 100L then
            printfn "  Warning: performance test failed."
    with
    | e ->
        test "test10 - Async.Parallel" false
        printfn "%s" (e.ToString())
#endif
(*
// performance of Async.Future
let test11() =
    let fibo_1() =
        Array.init 37 fibo

    // should be at least 30% faster if multi-core
    let fibo_2() =
        let compute n = async { return fibo n }
        let arr = Array.init 37 (fun n -> Async.SpawnFuture (compute n))
        arr |> Array.map (fun a -> a.Value)
  
    let (r1, t1), (r2, t2) = time fibo_1 (), time fibo_2 ()
    test "test11 - AsyncFuture" (r1 = r2)
    printfn "test11 - performance, ratio = %f, expect < 0.8" (float t2.Ticks / float t1.Ticks)
    if t2.Ticks > t1.Ticks * 80L / 100L then
        printfn "  Warning: performance test failed."
*)


// performance of Async.Generate
#if GenEqBug
let test12() =
    let fibo_1() =
        Array.init 37 fibo

    let fibo_2() =
        let compute n = async { return fibo n }
        Async.RunSynchronously (Async.Generate(37, compute, 37))

    try
        let (r1, t1), (r2, t2) = time fibo_1 (), time fibo_2 ()
        test "test12 - Async.Generate" (r1 = r2)
        printfn "test12 - performance, ratio = %f, expect < 0.8" (float t2.Ticks / float t1.Ticks)
        if t2.Ticks > t1.Ticks * 80L / 100L then
            printfn "  Warning: performance test failed."
    with
    | e ->
        test "test12 - performance" false
        printfn "%s" (e.ToString())
#endif

// Self-cancellation
let test13() =
    let a = async {
        try
            do Async.CancelDefaultToken()
            let! _ = async { return 1 } 
            do test "test13" false
        with
        | _ -> do test "test13" false }

    try       
        a |> Async.RunSynchronously |> ignore
        test "test13" false
    with
    | :? System.OperationCanceledException -> test "test13" true
    | _ -> test "test13" false


// Exceptions
let test14() =
    try
        fail |> Async.RunSynchronously |> ignore
        test "test14" false
    with
    | Failure "fail" -> test "test14" true
    | e -> 
        test "test14" false
        printfn "test14 caught exception was: %s" (e.ToString())


// Useful class: put "checkpoints" in the code.
// Check they are called in the right order.
type Path(str) =
    let mutable current = 0
    member p.Check n = check (str + " #" + string (current+1)) n (current+1)
                       current <- n

// Cancellation - TryCancelled
let test15() =
    let p = Path "test15 - cancellation"

    let cancel = async {
        do! Async.Sleep 100
        do failwith "fail" }

    let a = async {
        try
            use! holder = Async.OnCancel (fun _ -> p.Check 1)
            do! Async.Sleep 200
            do p.Check 2
            let! _ = async { return 1 } 
            do p.Check (-1)
        finally
            p.Check 3}
    try
        let a = Async.TryCancelled(a, (fun _ -> p.Check 4))
        let a = Async.TryCancelled(a, (fun _ -> p.Check 5))
        let a = Async.TryCancelled(a, (fun _ -> p.Check 6))
        Async.Parallel2(a, cancel)
        |> Async.RunSynchronously |> ignore
    with _ -> ()
#if NetCore
    Task.Delay(300).Wait()
#else
    System.Threading.Thread.Sleep(300)
#endif
    p.Check 7

// The same, without the cancellation
let test15b() =
    let p = Path "test15b, no cancellation"
    let a = async {
        try
            use! holder = Async.OnCancel (fun _ -> p.Check -1)
            do! Async.Sleep 200
            do p.Check 1
            let! _ = async { return 1 } 
            do p.Check 2
        finally
            p.Check 3}
    try
        let a = Async.TryCancelled(a, (fun _ -> p.Check -1))
        a |> Async.RunSynchronously |> ignore
    with _ -> ()
#if NetCore
    Task.Delay(100).Wait()
#else
    System.Threading.Thread.Sleep(100)
#endif

test1()
test2()
#if NetCore
#else
test3()
#endif
#if GenEqBug
test8()
test9()
#endif
test13()
test14()
// ToDo: 7/31/2008: Disabled because of probable timing issue.  QA needs to re-enable post-CTP.
// Tracked by bug FSharp 1.0:2891
//test15()
// ToDo: 7/31/2008: Disabled because of probable timing issue.  QA needs to re-enable post-CTP.
// Tracked by bug FSharp 1.0:2891
//test15b()

// performance (multi-core only)
if System.Environment.ProcessorCount > 1 then
#if GenEqBug
    test10()
    test12()
#else
    ()
#endif


// test cancellation, with a sub-computation
let test22() =
    let p = Path "test22"
    let a = async {
        do p.Check 1
#if NetCore
        do Task.Delay(200).Wait()
#else
        do System.Threading.Thread.Sleep(200)
#endif
        do p.Check 3
        let! _ = async { return 1 } 
        do p.Check -1
    }
    let run = async {
        try
            do! a
            do p.Check -1
        with _ -> do p.Check -1
    }
    let run = Async.TryCancelled(run, fun _ -> p.Check 4)
    let group = new System.Threading.CancellationTokenSource()
    Async.Start(run,group.Token)
#if NetCore
    Task.Delay(100).Wait()
#else
    System.Threading.Thread.Sleep(100)
#endif
    p.Check 2
    group.Cancel()
#if NetCore
    Task.Delay(200).Wait()
#else
    System.Threading.Thread.Sleep(200)
#endif
    p.Check 5

// ToDo: 7/25/2008: Disabled because of probable timing issue.  QA needs to re-enable post-CTP.
// Tracked by bug FSharp 1.0:2891
// test22()
    
module ParallelTest = 

    let Test() =
        let n = 10
        let controlWasReturnedToClientAlready = ref false
        // goal is invariant that client sees invariant 
        // numOutstandingWorkers=0 after Async.RunSynchronously call
        let numOutstandingWorkers = ref 0  
        let ex = new System.Exception()
        let failureHappened = ref false
        try
            let res = 
                Async.RunSynchronously 
                    (Async.Parallel 
                        [for i in 0..n-1 ->
                            async {
                                if i=0 then
                                    // let all other threads spin up before we fail
                                    while !numOutstandingWorkers <> n-1 do
                                        do! Async.Sleep(100) 
                                    failureHappened := true
                                    return raise ex
                                else
                                    use r = { new System.IDisposable with 
                                                  member x.Dispose() = // This gets run when the cancel happens
                                                      if i=n-1 then
                                                          // last guy waits a long time to ensure client is blocked
#if NetCore
                                                          Task.Delay(200).Wait()
#else
                                                          System.Threading.Thread.Sleep(2000)
#endif
                                                      if not(!controlWasReturnedToClientAlready) then
                                                          lock numOutstandingWorkers (fun() -> numOutstandingWorkers := !numOutstandingWorkers - 1) }
                                    // mark that we began
                                    lock numOutstandingWorkers (fun() -> numOutstandingWorkers := !numOutstandingWorkers + 1)
                                    // Note - this doesn't return - it must be cancelled
                                    while true do 
                                        do! Async.Sleep(100*n) 
                                    return 1 }]) 
            ()
        with
            | e when obj.ReferenceEquals(e,ex) -> ()
            | e2 -> 
                failureHappened := true
                check (sprintf "first exception was not returned to client, instead got: %s" (e2.ToString())) 1 0

        controlWasReturnedToClientAlready := true

        if !numOutstandingWorkers<> 0 then
            failureHappened := true
            check  "test failed because client got ahead of cleanup"    1 0

        if !failureHappened = false then
            check  "parallel-test-success"    1 1
#if ParallelBug
    Test()
#endif


#if NetCore
#else
// See bug 5570, check we do not switch threads
module CheckNoPumpingOrThreadSwitchingBecauseWeTrampolineSynchronousCode =
    let checkOnThread  msg expectedThreadId = 
        let currentId = System.Threading.Thread.CurrentThread.ManagedThreadId
        checkQuiet msg currentId expectedThreadId 

    async { let tid = System.Threading.Thread.CurrentThread.ManagedThreadId
            let ctxt = System.Threading.SynchronizationContext.Current
            let state =  ref 1
            for i = 0 to 10000 do 
                let! res = async { return 1+i } // a bind point to a synchronous process, we do not expect this to switch threads or pump
                
                
                // The execution of these Posts should be delayed until after the async has exited its synchronous code
                if ctxt <> null then 
                    ctxt.Post((fun _ -> 
                        //printfn "setting, tid = %d" System.Threading.Thread.CurrentThread.ManagedThreadId; 
                        state := 2), null) 
                if i % 50 = 0 then printfn "tick %d..." i
                checkOnThread "clkneoiwen thread check" tid 
                checkQuiet "cwnewe9wecokm" !state 1 } |> Async.StartImmediate

#if Portable
#else
open System.Windows.Forms

#if COMPILED
// See bug 5570, check we do not switch threads
module CheckNoPumpingBecauseWeTrampolineSynchronousCode =
    let checkOnThread  msg expectedThreadId = 
        let currentId = System.Threading.Thread.CurrentThread.ManagedThreadId
        checkQuiet msg currentId expectedThreadId 

    let form = new System.Windows.Forms.Form()
    form.Load.Add(fun _ -> 
    
        async { let tid = System.Threading.Thread.CurrentThread.ManagedThreadId
                let ctxt = System.Threading.SynchronizationContext.Current
                let state =  ref 1
                for i = 0 to 10000 do 
                    let! res = async { return 1+i } // a bind point to a synchronous process, we do not expect this to switch threads or pump

                    // The execution of these Posts should be delayed until after the async has exited its synchronous code
                    if ctxt <> null then 
                        ctxt.Post((fun _ -> 
                            //printfn "setting, tid = %d" System.Threading.Thread.CurrentThread.ManagedThreadId; 
                            state := 2), null) 
                    if i % 50 = 0 then printfn "tick %d..." i
                    checkOnThread "clkneoiwen thread check" tid 
                    checkQuiet "cwnewe9wecokm" !state 1 
                Application.Exit() } 
             |> Async.StartImmediate)

    Application.Run form             
    // Set the synchronization context back to its original value
    System.Threading.SynchronizationContext.SetSynchronizationContext(null);
    
#endif

#endif

#endif //NetCore

module CheckContinuationsMayNotBeCalledMoreThanOnce = 

    (try 
             Async.FromContinuations(fun (cont,_,_) -> cont(); cont()) |> Async.StartImmediate
             false
     with :? System.InvalidOperationException -> true)
    |> check "celkner091" true

    (try 
             Async.FromContinuations(fun (cont,econt,_) -> cont (); econt (Failure "fail")) |> Async.StartImmediate
             false
     with :? System.InvalidOperationException -> true)
    |> check "celkner092" true


    (try 
             Async.FromContinuations(fun (cont,econt,ccont) -> cont (); ccont (System.OperationCanceledException())) |> Async.StartImmediate 
             false
     with :? System.InvalidOperationException -> true)
    |> check "celkner093" true


    (try 
             Async.FromContinuations(fun (cont,econt,ccont) -> ccont (System.OperationCanceledException()); ccont (System.OperationCanceledException())) |> Async.StartImmediate 
             false
     with :? System.InvalidOperationException -> true)
    |> check "celkner094" true


module CheckStartImmediate = 

    // Check the async is executed immediately
    (let res = ref 1
     async { res := 2 } |> Async.StartImmediate
     res.Value)
    |> check "celkner091" 2


    // Check we catch the failure immediately
    (try 
         async { failwith "fail" } |> Async.StartImmediate 
         1
     with Failure _ -> 2)
    |> check "celkner091" 2

module Bug5770 =
    type exp = 
        | Var of string           
        | Lambda of string * exp           
        | Apply of exp * exp
    
    let pfoldExpr varF lamF appF exp =     
        let rec Loop e = async {
            match e with        
            | Var x -> return (varF x)        
            | Lambda (x, body) -> let! bodyAcc = Loop body
                                  return (lamF x bodyAcc)       
            | Apply (l, r) -> let! [| lAcc; rAcc |] = [| Loop l; Loop r |] |> Async.Parallel 
                              return (appF lAcc rAcc) }  
        Loop exp 
        
    let ptoString e =    
        pfoldExpr        
            (fun x -> sprintf "%s" x)        
            (fun x y -> sprintf "(\\%s.%s)" x y)        
            (fun x y -> sprintf "(%s %s)" x y)   
            e     
        |> Async.RunSynchronously 

    let e = Apply(Lambda("x", Var "x"), Lambda("y", Var "y"))
    let C e = Apply(e,e)
    let bigE = C(C(C(C(C(C(C(C(C(C(C(C(C(e)))))))))))))
    
    try
        for i = 1 to 10 do
            check (sprintf "dfgeyrtwq26: Async.Parallel spawning Parallel %d" i)
                (ptoString bigE |> ignore; "Complete")
                "Complete"
    with
    | e ->
        check "Bug 5770" true false
        printfn "%s" (e.ToString())



module Bug6086 =
    try
        let count = 200000
        let rec loop i : Async<string> = 
            async { if i <= 0 then return "finished"
                    else return! loop (i-1) }
        
        check "4dyeyuiqyhi3 - async"
            (loop count |> Async.RunSynchronously)
            "finished"
        
        let rec p i : Async<string> = async.Delay(fun () -> if i > 0 then  p (i-1) else async.Return("finished"))
        check "4dyeyuiqyhi3 - async.Delay"
            (loop count |> Async.RunSynchronously)
            "finished"
    with
    | e ->
        check "Bug6086" true false
        printfn "%s" (e.ToString())
    
module Bug850869 =
  let f1() = 
    async
      { use! a = Unchecked.defaultof<Async<System.IDisposable>>
        return true }

  let f2() = 
    async
      { use! A = Unchecked.defaultof<Async<System.IDisposable>>
        return true }         

module ExceptionInAsyncParallelOrHowToInvokeContinuationTwice = 
    
    let test() = 
        let pair = async {
            try
                let! r = 
                    [
                        async {
                            do! Async.Sleep 10000
                            return failwith "Should not be exercised"
                        }
                        async {
                            ignore (42/0) //this will throw
                            return 42
                        }
                    ] |> Async.Parallel
 
                return "OK"
            with :? System.DivideByZeroException -> return "OOPS"
        }
        let counter = ref 0
        let driver = async {
            let! r = pair
            incr counter
        }
        try
            Async.RunSynchronously driver
            !counter = 1
        with
            _ -> false

    check "ExceptionInAsyncParallelOrHowToInvokeContinuationTwice" (Seq.init 30 (ignore >> test) |> Seq.forall id) true
    


// [Asyncs] Cancellation inside Async.AwaitWaitHandle may release source WaitHandle
module Bug391710 =
    open System
    open System.Threading
 
    let mutable trace = List.empty<string>
    let Bug391710() = 
        use s = new ManualResetEvent(false)
        let cts = new CancellationTokenSource()

        let a1 = 
            async { let! _ok = Async.AwaitWaitHandle s
                    trace <- List.Cons("a1", trace)
            }

        let a2 = 
            async { let! _ok = Async.AwaitWaitHandle s
                    trace <- List.Cons("a2", trace)
            }

        Async.Start(a1, cancellationToken = cts.Token)
        Async.Start(a2)
#if NetCore
        Task.Delay(500).Wait();
#else
        System.Threading.Thread.Sleep(500)
#endif
        cts.Cancel()

    try
        Bug391710()
#if NetCore
        Task.Delay(500).Wait();
#else
        System.Threading.Thread.Sleep(2000)
#endif
        check "Check that cancellation of 'a1' does not trigger the signalling of 's' (Bug391710)" trace []
    with
    | e ->
        check "Bug391710" true false
        printfn "%s" (e.ToString())

// Some tests should not be run in the static constructor
let RunAll() = 
    BasicTests.Run()
    StartChildOutsideOfAsync.Run()
    SpawnTests.Run()
    AsBeginEndTests.AsBeginEndTest()
    AwaitEventTests.AwaitEventTest()
    OnCancelTests.Run()
#if GenEqBug
    GenerateTests.Run()
#endif
    ParallelTests.Run()
#if Portable
#else
    AsyncWaitOneTest1.Run()
    AsyncGenerateTests.Run()
#endif

#if ALL_IN_ONE
let RUN() = RunAll(); failures
#else
RunAll()
let aa =
  if not failures.IsEmpty then 
      stdout.WriteLine "Test Failed"
      exit 1
  else   
      stdout.WriteLine "Test Passed"
      log "ALL OK, HAPPY HOLIDAYS, MERRY CHRISTMAS!"
      System.IO.File.WriteAllText("test.ok","ok")
      exit 0
#endif