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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Tracing;
using System.Threading;
using Microsoft.PowerShell.Telemetry;

using Dbg = System.Management.Automation.Diagnostics;
#if LEGACYTELEMETRY
using Microsoft.PowerShell.Telemetry.Internal;
#endif

namespace System.Management.Automation.Runspaces.Internal
{
    /// <summary>
    /// Class which supports pooling remote powerShell runspaces
    /// on the client.
    /// </summary>
    internal sealed class RemoteRunspacePoolInternal : RunspacePoolInternal
    {
        #region Constructor

        /// <summary>
        /// Constructor which creates a RunspacePool using the
        /// supplied <paramref name="connectionInfo"/>, <paramref name="minRunspaces"/>
        /// and <paramref name="maxRunspaces"/>
        /// </summary>
        /// <param name="maxRunspaces">
        /// The maximum number of Runspaces that can exist in this pool.
        /// Should be greater than or equal to 1.
        /// </param>
        /// <param name="minRunspaces">
        /// The minimum number of Runspaces that can exist in this pool.
        /// Should be greater than or equal to 1.
        /// </param>
        /// <param name="typeTable">
        /// The TypeTable to use while deserializing/serializing remote objects.
        /// TypeTable has the following information used by serializer:
        ///   1. SerializationMethod
        ///   2. SerializationDepth
        ///   3. SpecificSerializationProperties
        /// TypeTable has the following information used by deserializer:
        ///   1. TargetTypeForDeserialization
        ///   2. TypeConverter
        /// </param>
        /// <param name="host">Host associated with this runspacepool.</param>
        /// <param name="applicationArguments">
        /// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
        /// </param>
        /// <param name="connectionInfo">The RunspaceConnectionInfo object
        /// which identifies this runspace pools connection to the server
        /// </param>
        /// <param name="name">Session name.</param>
        /// <exception cref="ArgumentException">
        /// Maximum runspaces is less than 1.
        /// Minimum runspaces is less than 1.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// ConnectionInfo specified is null
        /// </exception>
        internal RemoteRunspacePoolInternal(int minRunspaces,
            int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null)
            : base(minRunspaces, maxRunspaces)
        {
            if (connectionInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo");
            }

            PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor,
                    PSOpcode.Constructor, PSTask.CreateRunspace,
                    PSKeyword.UseAlwaysOperational,
                    instanceId.ToString(),
                    minPoolSz.ToString(CultureInfo.InvariantCulture),
                    maxPoolSz.ToString(CultureInfo.InvariantCulture));

            _connectionInfo = connectionInfo.Clone();

            this.host = host;
            ApplicationArguments = applicationArguments;
            AvailableForConnection = false;
            DispatchTable = new DispatchTable<object>();
            _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack<PowerShell>();

            if (!string.IsNullOrEmpty(name))
            {
                this.Name = name;
            }

            CreateDSHandler(typeTable);
        }

        /// <summary>
        /// Create a runspacepool object in the disconnected state.
        /// </summary>
        /// <param name="instanceId">Identifies remote session to connect.</param>
        /// <param name="name">Friendly name for runspace pool.</param>
        /// <param name="isDisconnected">Indicates whether the runspacepool is disconnected.</param>
        /// <param name="connectCommands">Array of commands associated with this runspace pool.</param>
        /// <param name="connectionInfo">Connection information for remote server.</param>
        /// <param name="host">PSHost object.</param>
        /// <param name="typeTable">TypeTable for object serialization/deserialization.</param>
        internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconnected,
            ConnectCommandInfo[] connectCommands, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
            : base(1, 1)
        {
            if (instanceId == Guid.Empty)
            {
                throw PSTraceSource.NewArgumentException(nameof(instanceId));
            }

            if (connectCommands == null)
            {
                throw PSTraceSource.NewArgumentNullException("ConnectCommandInfo[]");
            }

            if (connectionInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo");
            }

            if (connectionInfo is WSManConnectionInfo)
            {
                _connectionInfo = connectionInfo.Clone();
            }
            else
            {
                Dbg.Assert(false, "ConnectionInfo must be WSManConnectionInfo");
            }

            // Create the runspace pool object to have the same instanceId as the remote session.
            this.instanceId = instanceId;

            // This indicates that this is a disconnected remote runspace pool and min/max values
            // are currently unknown. These values will be updated once the object is connected.
            this.minPoolSz = -1;
            this.maxPoolSz = -1;

            PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor,
                    PSOpcode.Constructor, PSTask.CreateRunspace,
                    PSKeyword.UseAlwaysOperational,
                    instanceId.ToString(),
                    minPoolSz.ToString(CultureInfo.InvariantCulture),
                    maxPoolSz.ToString(CultureInfo.InvariantCulture));

            ConnectCommands = connectCommands;
            this.Name = name;
            this.host = host;
            DispatchTable = new DispatchTable<object>();
            _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack<PowerShell>();

            // Create this object in the disconnected state.
            SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Disconnected, null));

            CreateDSHandler(typeTable);

            AvailableForConnection = isDisconnected;
        }

        /// <summary>
        /// Helper method to create the dispatchTable and dataStructureHandler objects.
        /// </summary>
        private void CreateDSHandler(TypeTable typeTable)
        {
            DataStructureHandler = new ClientRunspacePoolDataStructureHandler(this, typeTable);

            // register for events from the data structure handler
            DataStructureHandler.RemoteHostCallReceived += HandleRemoteHostCalls;
            DataStructureHandler.StateInfoReceived += HandleStateInfoReceived;
            DataStructureHandler.RSPoolInitInfoReceived += HandleInitInfoReceived;
            DataStructureHandler.ApplicationPrivateDataReceived += HandleApplicationPrivateDataReceived;
            DataStructureHandler.SessionClosing += HandleSessionClosing;
            DataStructureHandler.SessionClosed += HandleSessionClosed;
            DataStructureHandler.SetMaxMinRunspacesResponseReceived += HandleResponseReceived;
            DataStructureHandler.URIRedirectionReported += HandleURIDirectionReported;
            DataStructureHandler.PSEventArgsReceived += HandlePSEventArgsReceived;
            DataStructureHandler.SessionDisconnected += HandleSessionDisconnected;
            DataStructureHandler.SessionReconnected += HandleSessionReconnected;
            DataStructureHandler.SessionRCDisconnecting += HandleSessionRCDisconnecting;
            DataStructureHandler.SessionCreateCompleted += HandleSessionCreateCompleted;
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// The connection associated with this runspace pool.
        /// </summary>
        public override RunspaceConnectionInfo ConnectionInfo
        {
            get
            {
                return _connectionInfo;
            }
        }

        /// <summary>
        /// The ClientRunspacePoolDataStructureHandler associated with this
        /// runspace pool.
        /// </summary>
        internal ClientRunspacePoolDataStructureHandler DataStructureHandler { get; private set; }

        /// <summary>
        /// List of CommandConnectInfo objects for each remote running command
        /// associated with this remote runspace pool.
        /// </summary>
        internal ConnectCommandInfo[] ConnectCommands { get; set; } = null;

        /// <summary>
        /// Gets and sets the name string for this runspace pool object.
        /// </summary>
        internal string Name
        {
            get { return _friendlyName; }

            set { _friendlyName = value ?? string.Empty; }
        }

        /// <summary>
        /// Indicates whether this runspace pools viable/available for connection.
        /// </summary>
        internal bool AvailableForConnection { get; private set; }

        /// <summary>
        /// Returns robust connection maximum retry time in milliseconds.
        /// </summary>
        internal int MaxRetryConnectionTime
        {
            get
            {
                return (DataStructureHandler != null) ? DataStructureHandler.MaxRetryConnectionTime : 0;
            }
        }

        /// <summary>
        /// Returns runspace pool availability.
        /// </summary>
        public override RunspacePoolAvailability RunspacePoolAvailability
        {
            get
            {
                RunspacePoolAvailability availability;
                if (stateInfo.State == RunspacePoolState.Disconnected)
                {
                    // Set availability for disconnected runspace pool in the
                    // same way it is set for runspaces.
                    availability = (AvailableForConnection) ?
                            RunspacePoolAvailability.None :     // Disconnected runspacepool available for connection.
                            RunspacePoolAvailability.Busy;      // Disconnected runspacepool unavailable for connection.
                }
                else
                {
                    availability = base.RunspacePoolAvailability;
                }

                return availability;
            }
        }

        /// <summary>
        /// Property to indicate that the debugger associated to this
        /// remote runspace is in debug stop mode.
        /// </summary>
        internal bool IsRemoteDebugStop
        {
            get;
            set;
        }

        #endregion

        #region internal Methods

        /// <summary>
        /// Resets the runspace state on a runspace pool with a single
        /// runspace.
        /// This is currently supported *only* for remote runspaces.
        /// </summary>
        /// <returns>True if successful.</returns>
        internal override bool ResetRunspaceState()
        {
            // Version check.  Reset Runspace is supported only on PSRP protocol
            // version 2.3 or greater.
            Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion;
            if ((remoteProtocolVersionDeclaredByServer == null) ||
                (remoteProtocolVersionDeclaredByServer < RemotingConstants.ProtocolVersion_2_3))
            {
                throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.ResetRunspaceStateNotSupportedOnServer);
            }

            long callId = 0;

            lock (syncObject)
            {
                callId = DispatchTable.CreateNewCallId();
                DataStructureHandler.SendResetRunspaceStateToServer(callId);
            }

            // This call blocks until the response is received.
            object response = DispatchTable.GetResponse(callId, false);
            return (bool)response;
        }

        /// <summary>
        /// Sets the maximum number of Runspaces that can be active concurrently
        /// in the pool. All requests above that number remain queued until
        /// runspaces become available.
        /// </summary>
        /// <param name="maxRunspaces">
        /// The maximum number of runspaces in the pool.
        /// </param>
        /// <returns>
        /// true if the change is successful; otherwise, false.
        /// </returns>
        /// <remarks>
        /// You cannot set the number of runspaces to a number smaller than
        /// the minimum runspaces.
        /// </remarks>
        internal override bool SetMaxRunspaces(int maxRunspaces)
        {
            bool isSizeIncreased = false;
            long callId = 0;

            lock (syncObject)
            {
                if (maxRunspaces < minPoolSz || maxRunspaces == maxPoolSz || stateInfo.State == RunspacePoolState.Closed
                    || stateInfo.State == RunspacePoolState.Closing || stateInfo.State == RunspacePoolState.Broken)
                {
                    return false;
                }

                // if the runspace pool is not opened as yet, or is in Disconnected state.
                // just change the value locally. No need to
                // send a message
                if (stateInfo.State == RunspacePoolState.BeforeOpen ||
                    stateInfo.State == RunspacePoolState.Disconnected)
                {
                    maxPoolSz = maxRunspaces;
                    return true;
                }

                // sending the message should be done within the lock
                // to ensure that multiple calls to SetMaxRunspaces
                // will be executed on the server in the order in which
                // they were called in the client
                callId = DispatchTable.CreateNewCallId();

                DataStructureHandler.SendSetMaxRunspacesToServer(maxRunspaces, callId);
            }

            // this call blocks until the response is received
            object response = DispatchTable.GetResponse(callId, false);

            isSizeIncreased = (bool)response;

            if (isSizeIncreased)
            {
                lock (syncObject)
                {
                    maxPoolSz = maxRunspaces;
                }
            }

            return isSizeIncreased;
        }

        /// <summary>
        /// Sets the minimum number of Runspaces that the pool maintains
        /// in anticipation of new requests.
        /// </summary>
        /// <param name="minRunspaces">
        /// The minimum number of runspaces in the pool.
        /// </param>
        /// <returns>
        /// true if the change is successful; otherwise, false.
        /// </returns>
        /// <remarks>
        /// You cannot set the number of idle runspaces to a number smaller than
        /// 1 or greater than maximum number of active runspaces.
        /// </remarks>
        internal override bool SetMinRunspaces(int minRunspaces)
        {
            bool isSizeDecreased = false;
            long callId = 0;

            lock (syncObject)
            {
                if ((minRunspaces < 1) || (minRunspaces > maxPoolSz) || (minRunspaces == minPoolSz)
                    || stateInfo.State == RunspacePoolState.Closed || stateInfo.State == RunspacePoolState.Closing ||
                    stateInfo.State == RunspacePoolState.Broken)
                {
                    return false;
                }

                // if the runspace pool is not opened as yet, or is in Disconnected state.
                // just change the value locally. No need to
                // send a message
                if (stateInfo.State == RunspacePoolState.BeforeOpen ||
                    stateInfo.State == RunspacePoolState.Disconnected)
                {
                    minPoolSz = minRunspaces;
                    return true;
                }

                // sending the message should be done within the lock
                // to ensure that multiple calls to SetMinRunspaces
                // will be executed on the server in the order in which
                // they were called in the client
                callId = DispatchTable.CreateNewCallId();

                DataStructureHandler.SendSetMinRunspacesToServer(minRunspaces, callId);
            }

            // this call blocks until the response is received
            object response = DispatchTable.GetResponse(callId, false);

            isSizeDecreased = (bool)response;

            if (isSizeDecreased)
            {
                lock (syncObject)
                {
                    minPoolSz = minRunspaces;
                }
            }

            return isSizeDecreased;
        }

        /// <summary>
        /// Retrieves the number of runspaces available at the time of calling
        /// this method from the remote server.
        /// </summary>
        /// <returns>The number of runspaces available in the pool.</returns>
        internal override int GetAvailableRunspaces()
        {
            int availableRunspaces = 0;
            long callId = 0;

            lock (syncObject)
            {
                // if the runspace pool is opened we need to
                // get the value from the server, else
                // return maxrunspaces
                if (stateInfo.State == RunspacePoolState.Opened)
                {
                    // sending the message should be done within the lock
                    // to ensure that multiple calls to GetAvailableRunspaces
                    // will be executed on the server in the order in which
                    // they were called in the client
                    callId = DispatchTable.CreateNewCallId();
                }
                else if (stateInfo.State != RunspacePoolState.BeforeOpen && stateInfo.State != RunspacePoolState.Opening)
                {
                    throw new InvalidOperationException(HostInterfaceExceptionsStrings.RunspacePoolNotOpened);
                }
                else
                {
                    return maxPoolSz;
                }

                DataStructureHandler.SendGetAvailableRunspacesToServer(callId);
            }

            // this call blocks until the response is received
            object response = DispatchTable.GetResponse(callId, 0);
            availableRunspaces = (int)response;

            return availableRunspaces;
        }

        /// <summary>
        /// The server sent application private data.  Store the data so that user
        /// can get it later.
        /// </summary>
        /// <param name="eventArgs">Argument describing this event.</param>
        /// <param name="sender">Sender of this event.</param>
        internal void HandleApplicationPrivateDataReceived(object sender,
            RemoteDataEventArgs<PSPrimitiveDictionary> eventArgs)
        {
            this.SetApplicationPrivateData(eventArgs.Data);
        }

        internal void HandleInitInfoReceived(object sender,
                        RemoteDataEventArgs<RunspacePoolInitInfo> eventArgs)
        {
            RunspacePoolStateInfo info = new RunspacePoolStateInfo(RunspacePoolState.Opened, null);

            bool raiseEvents = false;

            lock (syncObject)
            {
                minPoolSz = eventArgs.Data.MinRunspaces;
                maxPoolSz = eventArgs.Data.MaxRunspaces;
                if (stateInfo.State == RunspacePoolState.Connecting)
                {
                    ResetDisconnectedOnExpiresOn();

                    raiseEvents = true;
                    SetRunspacePoolState(info);
                }
            }

            if (raiseEvents)
            {
                // Private application data is sent after (post) connect.  We need
                // to wait for application data before raising the state change
                // Connecting -> Opened event.
                ThreadPool.QueueUserWorkItem(WaitAndRaiseConnectEventsProc, info);
            }
        }

        /// <summary>
        /// The state of the server RunspacePool has changed. Handle
        /// the same and reflect local states accordingly.
        /// </summary>
        /// <param name="eventArgs">Argument describing this event.</param>
        /// <param name="sender">Sender of this event.</param>
        internal void HandleStateInfoReceived(object sender,
            RemoteDataEventArgs<RunspacePoolStateInfo> eventArgs)
        {
            RunspacePoolStateInfo newStateInfo = eventArgs.Data;
            bool raiseEvents = false;

            Dbg.Assert(newStateInfo != null, "state information should not be null");

            if (newStateInfo.State == RunspacePoolState.Opened)
            {
                lock (syncObject)
                {
                    if (stateInfo.State == RunspacePoolState.Opening)
                    {
                        SetRunspacePoolState(newStateInfo);
                        raiseEvents = true;
                    }
                }

                if (raiseEvents)
                {
                    // this needs to be done outside the lock to avoid a
                    // deadlock scenario
                    RaiseStateChangeEvent(stateInfo);
                    SetOpenAsCompleted();
                }
            }
            else if (newStateInfo.State == RunspacePoolState.Closed || newStateInfo.State == RunspacePoolState.Broken)
            {
                bool doClose = false;

                lock (syncObject)
                {
                    if (stateInfo.State == RunspacePoolState.Closed || stateInfo.State == RunspacePoolState.Broken)
                    {
                        // there is nothing to do here
                        return;
                    }

                    if (stateInfo.State == RunspacePoolState.Opening
                     || stateInfo.State == RunspacePoolState.Opened
                     || stateInfo.State == RunspacePoolState.Closing)
                    {
                        doClose = true;
                        SetRunspacePoolState(newStateInfo);
                    }
                }

                if (doClose)
                {
                    // if closeAsyncResult is null, BeginClose is not called. That means
                    // we are getting close event from server, in this case release the
                    // local resources
                    if (_closeAsyncResult == null)
                    {
                        // Close the local resources.
                        DataStructureHandler.CloseRunspacePoolAsync();
                    }

                    // Delay notifying upper layers of finished state change event
                    // until after transport close ack is received (HandleSessionClosed handler).
                }
            }
        }

        /// <summary>
        /// A host call has been proxied from the server which needs to
        /// be executed.
        /// </summary>
        /// <param name="sender">Sender of this event.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        internal void HandleRemoteHostCalls(object sender,
            RemoteDataEventArgs<RemoteHostCall> eventArgs)
        {
            if (HostCallReceived != null)
            {
                HostCallReceived.SafeInvoke(sender, eventArgs);
            }
            else
            {
                RemoteHostCall hostCall = eventArgs.Data;

                if (hostCall.IsVoidMethod)
                {
                    hostCall.ExecuteVoidMethod(host);
                }
                else
                {
                    RemoteHostResponse remoteHostResponse = hostCall.ExecuteNonVoidMethod(host);
                    DataStructureHandler.SendHostResponseToServer(remoteHostResponse);
                }
            }
        }

        internal PSHost Host
        {
            get
            {
                return host;
            }
        }

        /// <summary>
        /// Application arguments to use when opening a remote session.
        /// </summary>
        internal PSPrimitiveDictionary ApplicationArguments { get; }

        /// <summary>
        /// Private data to be used by applications built on top of PowerShell.
        ///
        /// Remote runspace pool gets its application private data from the server (when creating the remote runspace pool)
        /// - calling this method on a remote runspace will block until the data is received from the server.
        /// - unless the runspace is disconnected and data hasn't been received in which case it returns null immediately.
        /// </summary>
        internal override PSPrimitiveDictionary GetApplicationPrivateData()
        {
            if (this.RunspacePoolStateInfo.State == RunspacePoolState.Disconnected &&
                !_applicationPrivateDataReceived.WaitOne(0))
            {
                // Runspace pool was disconnected before application data was returned.  Application
                // data cannot be returned with the runspace pool disconnected so return null.
                return null;
            }

            return _applicationPrivateData;
        }

        internal void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData)
        {
            lock (this.syncObject)
            {
                if (_applicationPrivateDataReceived.WaitOne(0))
                {
                    return; // ignore server's attempt to set application private data if it has already been set
                }

                _applicationPrivateData = applicationPrivateData;
                _applicationPrivateDataReceived.Set();

                foreach (Runspace runspace in this.runspaceList)
                {
                    runspace.SetApplicationPrivateData(applicationPrivateData);
                }
            }
        }

        internal override void PropagateApplicationPrivateData(Runspace runspace)
        {
            if (_applicationPrivateDataReceived.WaitOne(0))
            {
                runspace.SetApplicationPrivateData(this.GetApplicationPrivateData());
            }
        }

        private PSPrimitiveDictionary _applicationPrivateData;
        private readonly ManualResetEvent _applicationPrivateDataReceived = new ManualResetEvent(false);

        /// <summary>
        /// This event is raised, when a host call is for a remote runspace
        /// which this runspace pool wraps.
        /// </summary>
        internal event EventHandler<RemoteDataEventArgs<RemoteHostCall>> HostCallReceived;

        /// <summary>
        /// EventHandler used to report connection URI redirections to the application.
        /// </summary>
        internal event EventHandler<RemoteDataEventArgs<Uri>> URIRedirectionReported;

        /// <summary>
        /// Notifies the successful creation of the runspace session.
        /// </summary>
        internal event EventHandler<CreateCompleteEventArgs> SessionCreateCompleted;

        /// <summary>
        /// </summary>
        /// <param name="shell"></param>
        internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell)
        {
            DataStructureHandler.CreatePowerShellOnServerAndInvoke(shell);

            // send any input that may be available
            if (!shell.NoInput)
            {
                shell.SendInput();
            }
        }

        /// <summary>
        /// Add a ClientPowerShellDataStructureHandler to ClientRunspaceDataStructureHandler list.
        /// </summary>
        /// <param name="psShellInstanceId">PowerShell Instance Id.</param>
        /// <param name="psDSHandler">ClientPowerShellDataStructureHandler for PowerShell.</param>
        internal void AddRemotePowerShellDSHandler(Guid psShellInstanceId, ClientPowerShellDataStructureHandler psDSHandler)
        {
            DataStructureHandler.AddRemotePowerShellDSHandler(psShellInstanceId, psDSHandler);
        }

        /// <summary>
        /// Returns true if Runspace supports disconnect.
        /// </summary>
        internal bool CanDisconnect
        {
            get
            {
                Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion;
                if (remoteProtocolVersionDeclaredByServer != null && DataStructureHandler != null)
                {
                    // Disconnect/Connect support is currently only provided by the WSMan transport
                    // that is running PSRP protocol version 2.2 and greater.
                    return (remoteProtocolVersionDeclaredByServer >= RemotingConstants.ProtocolVersion_2_2 &&
                            DataStructureHandler.EndpointSupportsDisconnect);
                }

                return false;
            }
        }

        /// <summary>
        /// Returns the WinRM protocol version object for this runspace
        /// pool connection.
        /// </summary>
        internal Version PSRemotingProtocolVersion
        {
            get
            {
                Version winRMProtocolVersion = null;

                PSPrimitiveDictionary psPrimitiveDictionary = GetApplicationPrivateData();
                if (psPrimitiveDictionary != null)
                {
                    PSPrimitiveDictionary.TryPathGet(
                        psPrimitiveDictionary,
                        out winRMProtocolVersion,
                        PSVersionInfo.PSVersionTableName,
                        PSVersionInfo.PSRemotingProtocolVersionName);
                }

                return winRMProtocolVersion;
            }
        }

        /// <summary>
        /// Push a running PowerShell onto the stack.
        /// </summary>
        /// <param name="ps">PowerShell.</param>
        internal void PushRunningPowerShell(PowerShell ps)
        {
            Dbg.Assert(ps != null, "Caller should not pass in null reference.");
            _runningPowerShells.Push(ps);
        }

        /// <summary>
        /// Pop the currently running PowerShell from stack.
        /// </summary>
        /// <returns>PowerShell.</returns>
        internal PowerShell PopRunningPowerShell()
        {
            PowerShell powershell;
            if (_runningPowerShells.TryPop(out powershell))
            {
                return powershell;
            }

            return null;
        }

        /// <summary>
        /// Return the current running PowerShell.
        /// </summary>
        /// <returns>PowerShell.</returns>
        internal PowerShell GetCurrentRunningPowerShell()
        {
            PowerShell powershell;
            if (_runningPowerShells.TryPeek(out powershell))
            {
                return powershell;
            }

            return null;
        }

        #endregion Internal Methods

        #region Protected Methods

        /// <summary>
        /// Opens the runspacepool synchronously / asynchronously.
        /// Runspace pool must be opened before it can be used.
        /// </summary>
        /// <param name="isAsync">
        /// true to open asynchronously
        /// </param>
        /// <param name="callback">
        /// A AsyncCallback to call once the BeginOpen completes.
        /// </param>
        /// <param name="asyncState">
        /// A user supplied state to call the <paramref name="callback"/>
        /// with.
        /// </param>
        /// <returns>
        /// asyncResult object to monitor status of the async
        /// open operation. This is returned only if <paramref name="isAsync"/>
        /// is true.
        /// </returns>
        /// <exception cref="InvalidRunspacePoolStateException">
        /// Cannot open RunspacePool because RunspacePool is not in
        /// the BeforeOpen state.
        /// </exception>
        /// <exception cref="OutOfMemoryException">
        /// There is not enough memory available to start this asynchronously.
        /// </exception>
        protected override IAsyncResult CoreOpen(bool isAsync, AsyncCallback callback,
            object asyncState)
        {
            PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
            PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open,
                            PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational);

            // Telemetry here - remote session
            ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.RemoteSessionOpen, isAsync.ToString());
#if LEGACYTELEMETRY
            TelemetryAPI.ReportRemoteSessionCreated(_connectionInfo);
#endif

            lock (syncObject)
            {
                AssertIfStateIsBeforeOpen();

                stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opening, null);
            }

            // BUGBUG: the following comment needs to be validated
            // only one thread will reach here, so no need
            // to lock
            RaiseStateChangeEvent(stateInfo);

            RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(
                    instanceId, callback, asyncState, true);

            _openAsyncResult = asyncResult;

            // send a message using the data structure handler to open the RunspacePool
            // on the remote server
            DataStructureHandler.CreateRunspacePoolAndOpenAsync();

            return asyncResult;
        }

        #endregion Protected Methods

        #region Public Methods

        /// <summary>
        /// Synchronous open.
        /// </summary>
        public override void Open()
        {
            IAsyncResult asyncResult = BeginOpen(null, null);

            EndOpen(asyncResult);
        }

        /// <summary>
        /// Closes the RunspacePool and cleans all the internal
        /// resources. This will close all the runspaces in the
        /// runspacepool and release all the async operations
        /// waiting for a runspace. If the pool is already closed
        /// or broken or closing this will just return.
        /// </summary>
        /// <exception cref="InvalidRunspacePoolStateException">
        /// Cannot close the RunspacePool because RunspacePool is
        /// in Closing state.
        /// </exception>
        public override void Close()
        {
            // close and wait
            IAsyncResult asyncResult = BeginClose(null, null);
            EndClose(asyncResult);
        }

        /// <summary>
        /// Closes the RunspacePool asynchronously. To get the exceptions
        /// that might have occurred, call EndOpen.
        /// </summary>
        /// <param name="callback">
        /// An AsyncCallback to call once the BeginClose completes
        /// </param>
        /// <param name="asyncState">
        /// A user supplied state to call the <paramref name="callback"/>
        /// with
        /// </param>
        /// <returns>
        /// An AsyncResult object to monitor the state of the async
        /// operation
        /// </returns>
        public override IAsyncResult BeginClose(AsyncCallback callback, object asyncState)
        {
            bool raiseEvents = false;
            bool skipClosing = false;
            RunspacePoolStateInfo copyState = new RunspacePoolStateInfo(RunspacePoolState.BeforeOpen, null);
            RunspacePoolAsyncResult asyncResult = null;

            lock (syncObject)
            {
                if ((stateInfo.State == RunspacePoolState.Closed) ||
                    (stateInfo.State == RunspacePoolState.Broken))
                {
                    skipClosing = true;
                    asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
                }
                else if (stateInfo.State == RunspacePoolState.BeforeOpen)
                {
                    copyState = stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closed, null);
                    raiseEvents = true;
                    skipClosing = true;
                    _closeAsyncResult = null;
                    asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
                }
                else if (stateInfo.State == RunspacePoolState.Opened ||
                         stateInfo.State == RunspacePoolState.Opening)
                {
                    copyState = stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closing, null);
                    _closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
                    asyncResult = _closeAsyncResult;
                    raiseEvents = true;
                }
                else if (stateInfo.State == RunspacePoolState.Disconnected ||
                         stateInfo.State == RunspacePoolState.Disconnecting ||
                         stateInfo.State == RunspacePoolState.Connecting)
                {
                    // Continue with closing so the PSRP layer is aware that the client side session is
                    // being closed.  This will result in a broken session on the client.
                    _closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false);
                    asyncResult = _closeAsyncResult;
                }
                else if (stateInfo.State == RunspacePoolState.Closing)
                {
                    return _closeAsyncResult;
                }
            }

            // raise the events outside the lock
            if (raiseEvents)
            {
                RaiseStateChangeEvent(copyState);
            }

            if (!skipClosing)
            {
                // SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Closing, null), true);

                // send a message using the data structure handler to close the RunspacePool
                // on the remote server
                DataStructureHandler.CloseRunspacePoolAsync();
            }
            else
            {
                // signal the wait handle
                asyncResult.SetAsCompleted(null);
            }

            return asyncResult;
        }

        /// <summary>
        /// Synchronous disconnect.
        /// </summary>
        public override void Disconnect()
        {
            IAsyncResult asyncResult = BeginDisconnect(null, null);

            EndDisconnect(asyncResult);
        }

        /// <summary>
        /// Asynchronous disconnect.
        /// </summary>
        /// <param name="callback">AsyncCallback object.</param>
        /// <param name="state">State object.</param>
        /// <returns>IAsyncResult.</returns>
        public override IAsyncResult BeginDisconnect(AsyncCallback callback, object state)
        {
            if (!CanDisconnect)
            {
                throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.DisconnectNotSupportedOnServer);
            }

            RunspacePoolState currentState;
            bool raiseEvents = false;
            lock (syncObject)
            {
                currentState = stateInfo.State;
                if (currentState == RunspacePoolState.Opened)
                {
                    RunspacePoolStateInfo newStateInfo = new RunspacePoolStateInfo(RunspacePoolState.Disconnecting, null);

                    SetRunspacePoolState(newStateInfo);
                    raiseEvents = true;
                }
            }

            // Raise events outside of lock.
            if (raiseEvents)
            {
                RaiseStateChangeEvent(this.stateInfo);
            }

            if (currentState == RunspacePoolState.Opened)
            {
                RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult(
                    instanceId, callback, state, false);

                _disconnectAsyncResult = asyncResult;
                DataStructureHandler.DisconnectPoolAsync();

                // Return local reference to async object since the class member can
                // be asynchronously nulled if the session closes suddenly.
                return asyncResult;
            }
            else
            {
                string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Opened, stateInfo.State);
                InvalidRunspacePoolStateException invalidStateException = new InvalidRunspacePoolStateException(message,
                        stateInfo.State, RunspacePoolState.Opened);

                throw invalidStateException;
            }
        }

        /// <summary>
        /// Waits for BeginDisconnect operation to complete.
        /// </summary>
        /// <param name="asyncResult">IAsyncResult object.</param>
        public override void EndDisconnect(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
            }

            RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult;

            if ((rsAsyncResult == null) ||
                (rsAsyncResult.OwnerId != instanceId) ||
                (rsAsyncResult.IsAssociatedWithAsyncOpen))
            {
                throw PSTraceSource.NewArgumentException(nameof(asyncResult),
                                                         RunspacePoolStrings.AsyncResultNotOwned,
                                                         "IAsyncResult",
                                                         "BeginOpen");
            }

            rsAsyncResult.EndInvoke();
        }

        /// <summary>
        /// Synchronous connect.
        /// </summary>
        public override void Connect()
        {
            IAsyncResult asyncResult = BeginConnect(null, null);

            EndConnect(asyncResult);
        }

        /// <summary>
        /// Asynchronous connect.
        /// </summary>
        /// <param name="callback">ASyncCallback object.</param>
        /// <param name="state">State Object.</param>
        /// <returns>IAsyncResult.</returns>
        public override IAsyncResult BeginConnect(AsyncCallback callback, object state)
        {
            if (!AvailableForConnection)
            {
                throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.CannotConnect);
            }

            RunspacePoolState currentState;
            bool raiseEvents = false;
            lock (syncObject)
            {
                currentState = stateInfo.State;
                if (currentState == RunspacePoolState.Disconnected)
                {
                    RunspacePoolStateInfo newStateInfo = new RunspacePoolStateInfo(RunspacePoolState.Connecting, null);

                    SetRunspacePoolState(newStateInfo);
                    raiseEvents = true;
                }
            }

            // Raise events outside of lock.
            if (raiseEvents)
            {
                RaiseStateChangeEvent(this.stateInfo);
            }

            raiseEvents = false;

            if (currentState == RunspacePoolState.Disconnected)
            {
                // Assign to local variable to ensure we always pass a non-null value.
                // The async class members can be nulled out if the session closes suddenly.
                RunspacePoolAsyncResult ret = new RunspacePoolAsyncResult(
                    instanceId, callback, state, false);

                if (_canReconnect)
                {
                    // This indicates a reconnect scenario where this object instance was previously
                    // disconnected.
                    _reconnectAsyncResult = ret;
                    DataStructureHandler.ReconnectPoolAsync();
                }
                else
                {
                    // This indicates a reconstruction scenario where this object was created
                    // in the disconnect state and is being connected for the first time.
                    _openAsyncResult = ret;
                    DataStructureHandler.ConnectPoolAsync();
                }

                if (raiseEvents)
                {
                    RaiseStateChangeEvent(this.stateInfo);
                }

                return ret;
            }
            else
            {
                string message = StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolState, RunspacePoolState.Disconnected, stateInfo.State);
                InvalidRunspacePoolStateException invalidStateException = new InvalidRunspacePoolStateException(message,
                        stateInfo.State, RunspacePoolState.Disconnected);

                throw invalidStateException;
            }
        }

        /// <summary>
        /// Waits for BeginConnect to complete.
        /// </summary>
        /// <param name="asyncResult">IAsyncResult object.</param>
        public override void EndConnect(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(asyncResult));
            }

            RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult;

            if ((rsAsyncResult == null) ||
                (rsAsyncResult.OwnerId != instanceId) ||
                (rsAsyncResult.IsAssociatedWithAsyncOpen))
            {
                throw PSTraceSource.NewArgumentException(nameof(asyncResult),
                                                         RunspacePoolStrings.AsyncResultNotOwned,
                                                         "IAsyncResult",
                                                         "BeginOpen");
            }

            rsAsyncResult.EndInvoke();
        }

        /// <summary>
        /// Creates an array of PowerShell objects that are in the Disconnected state for
        /// all currently disconnected running commands associated with this runspace pool.
        /// </summary>
        /// <returns>Array of PowerShell objects.</returns>
        public override Collection<PowerShell> CreateDisconnectedPowerShells(RunspacePool runspacePool)
        {
            Collection<PowerShell> psCollection = new Collection<PowerShell>();

            if (ConnectCommands == null)
            {
                // Throw error indicating that this runspacepool is not configured for
                // reconstructing commands.
                string msg = StringUtil.Format(RunspacePoolStrings.CannotReconstructCommands, this.Name);
                throw new InvalidRunspacePoolStateException(msg);
            }

            // Get list of all disconnected commands associated with this runspace pool.
            foreach (ConnectCommandInfo connectCmdInfo in ConnectCommands)
            {
                psCollection.Add(new PowerShell(connectCmdInfo, runspacePool));
            }

            return psCollection;
        }

        /// <summary>
        /// Returns RunspacePool capabilities.
        /// </summary>
        /// <returns>RunspacePoolCapability.</returns>
        public override RunspacePoolCapability GetCapabilities()
        {
            RunspacePoolCapability returnCaps = RunspacePoolCapability.Default;

            if (CanDisconnect)
            {
                returnCaps |= RunspacePoolCapability.SupportsDisconnect;
            }

            return returnCaps;
        }

        #endregion Public Methods

        #region Static methods

        internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
        {
            if (connectionInfo is not WSManConnectionInfo wsmanConnectionInfoParam)
            {
                // Disconnect-Connect currently only supported by WSMan.
                throw new NotSupportedException();
            }

            List<RunspacePool> discRunspacePools = new List<RunspacePool>();

            // Enumerate all runspacepools
            Collection<PSObject> runspaceItems = RemoteRunspacePoolEnumeration.GetRemotePools(wsmanConnectionInfoParam);
            foreach (PSObject rsObject in runspaceItems)
            {
                // Create a new WSMan connection info object for each returned runspace pool.
                WSManConnectionInfo wsmanConnectionInfo = wsmanConnectionInfoParam.Copy();

                PSPropertyInfo pspShellId = rsObject.Properties["ShellId"];
                PSPropertyInfo pspState = rsObject.Properties["State"];
                PSPropertyInfo pspName = rsObject.Properties["Name"];
                PSPropertyInfo pspResourceUri = rsObject.Properties["ResourceUri"];

                if (pspShellId == null || pspState == null || pspName == null || pspResourceUri == null)
                {
                    continue;
                }

                string strName = pspName.Value.ToString();
                string strShellUri = pspResourceUri.Value.ToString();
                bool isDisconnected = pspState.Value.ToString().Equals("Disconnected", StringComparison.OrdinalIgnoreCase);
                Guid shellId = Guid.Parse(pspShellId.Value.ToString());

                // Filter returned items for PowerShell sessions.
                if (!strShellUri.StartsWith(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // Update wsmanconnection information with server settings.
                UpdateWSManConnectionInfo(wsmanConnectionInfo, rsObject);
                // Ensure that EnableNetworkAccess property is always enabled for reconstructed runspaces.
                wsmanConnectionInfo.EnableNetworkAccess = true;

                // Compute runspace DisconnectedOn and ExpiresOn fields.
                if (isDisconnected)
                {
                    DateTime? disconnectedOn;
                    DateTime? expiresOn;
                    ComputeDisconnectedOnExpiresOn(rsObject, out disconnectedOn, out expiresOn);
                    wsmanConnectionInfo.DisconnectedOn = disconnectedOn;
                    wsmanConnectionInfo.ExpiresOn = expiresOn;
                }

                List<ConnectCommandInfo> connectCmdInfos = new List<ConnectCommandInfo>();

                // Enumerate all commands on runspace pool.
                Collection<PSObject> commandItems;
                try
                {
                    commandItems = RemoteRunspacePoolEnumeration.GetRemoteCommands(shellId, wsmanConnectionInfo);
                }
                catch (CmdletInvocationException e)
                {
                    if (e.InnerException != null && e.InnerException is InvalidOperationException)
                    {
                        // If we cannot successfully retrieve command information then this runspace
                        // object we are building is invalid and must be skipped.
                        continue;
                    }

                    throw;
                }

                foreach (PSObject cmdObject in commandItems)
                {
                    PSPropertyInfo pspCommandId = cmdObject.Properties["CommandId"];
                    PSPropertyInfo pspCommandLine = cmdObject.Properties["CommandLine"];

                    if (pspCommandId == null)
                    {
                        Dbg.Assert(false, "Should not get an empty command Id from a remote runspace pool.");
                        continue;
                    }

                    string cmdLine = (pspCommandLine != null) ? pspCommandLine.Value.ToString() : string.Empty;
                    Guid cmdId = Guid.Parse(pspCommandId.Value.ToString());

                    connectCmdInfos.Add(new ConnectCommandInfo(cmdId, cmdLine));
                }

                // At this point we don't know if the runspace pool we want to connect to has just one runspace
                // (a RemoteRunspace/PSSession) or multiple runspaces in its pool.  We do have an array of
                // running command information which will indicate a runspace pool if the count is gt one.
                RunspacePool runspacePool = new RunspacePool(isDisconnected, shellId, strName,
                    connectCmdInfos.ToArray(), wsmanConnectionInfo, host, typeTable);
                discRunspacePools.Add(runspacePool);
            }

            return discRunspacePools.ToArray();
        }

        internal static RunspacePool GetRemoteRunspacePool(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable)
        {
            List<ConnectCommandInfo> connectCmdInfos = new List<ConnectCommandInfo>();
            if (commandId != null)
            {
                connectCmdInfos.Add(new ConnectCommandInfo(commandId.Value, string.Empty));
            }

            return new RunspacePool(true, sessionId, string.Empty, connectCmdInfos.ToArray(), connectionInfo, host, typeTable);
        }

        private static void UpdateWSManConnectionInfo(
            WSManConnectionInfo wsmanConnectionInfo,
            PSObject rsInfoObject)
        {
            PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"];
            PSPropertyInfo pspBufferMode = rsInfoObject.Properties["BufferMode"];
            PSPropertyInfo pspResourceUri = rsInfoObject.Properties["ResourceUri"];
            PSPropertyInfo pspLocale = rsInfoObject.Properties["Locale"];
            PSPropertyInfo pspDataLocale = rsInfoObject.Properties["DataLocale"];
            PSPropertyInfo pspCompressionMode = rsInfoObject.Properties["CompressionMode"];
            PSPropertyInfo pspEncoding = rsInfoObject.Properties["Encoding"];
            PSPropertyInfo pspProfile = rsInfoObject.Properties["ProfileLoaded"];
            PSPropertyInfo pspMaxIdleTimeout = rsInfoObject.Properties["MaxIdleTimeout"];

            if (pspIdleTimeOut != null)
            {
                int idleTimeout;
                if (GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout))
                {
                    wsmanConnectionInfo.IdleTimeout = idleTimeout;
                }
            }

            if (pspBufferMode != null)
            {
                string bufferingMode = pspBufferMode.Value as string;
                if (bufferingMode != null)
                {
                    OutputBufferingMode outputBufferingMode;
                    if (Enum.TryParse<OutputBufferingMode>(bufferingMode, out outputBufferingMode))
                    {
                        // Update connection info.
                        wsmanConnectionInfo.OutputBufferingMode = outputBufferingMode;
                    }
                }
            }

            if (pspResourceUri != null)
            {
                string strShellUri = pspResourceUri.Value as string;
                if (strShellUri != null)
                {
                    wsmanConnectionInfo.ShellUri = strShellUri;
                }
            }

            if (pspLocale != null)
            {
                string localString = pspLocale.Value as string;
                if (localString != null)
                {
                    try
                    {
                        wsmanConnectionInfo.UICulture = new CultureInfo(localString);
                    }
                    catch (ArgumentException)
                    { }
                }
            }

            if (pspDataLocale != null)
            {
                string dataLocalString = pspDataLocale.Value as string;
                if (dataLocalString != null)
                {
                    try
                    {
                        wsmanConnectionInfo.Culture = new CultureInfo(dataLocalString);
                    }
                    catch (ArgumentException)
                    { }
                }
            }

            if (pspCompressionMode != null)
            {
                string compressionModeString = pspCompressionMode.Value as string;
                if (compressionModeString != null)
                {
                    wsmanConnectionInfo.UseCompression = !compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase);
                }
            }

            if (pspEncoding != null)
            {
                string encodingString = pspEncoding.Value as string;
                if (encodingString != null)
                {
                    wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase);
                }
            }

            if (pspProfile != null)
            {
                string machineProfileLoadedString = pspProfile.Value as string;
                if (machineProfileLoadedString != null)
                {
                    wsmanConnectionInfo.NoMachineProfile = !machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase);
                }
            }

            if (pspMaxIdleTimeout != null)
            {
                int maxIdleTimeout;
                if (GetTimeIntValue(pspMaxIdleTimeout.Value as string, out maxIdleTimeout))
                {
                    wsmanConnectionInfo.MaxIdleTimeout = maxIdleTimeout;
                }
            }
        }

        private static void ComputeDisconnectedOnExpiresOn(
            PSObject rsInfoObject,
            out DateTime? disconnectedOn,
            out DateTime? expiresOn)
        {
            PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"];
            PSPropertyInfo pspShellInactivity = rsInfoObject.Properties["ShellInactivity"];

            if (pspIdleTimeOut != null && pspShellInactivity != null)
            {
                string shellInactivityString = pspShellInactivity.Value as string;
                int idleTimeout;
                if ((shellInactivityString != null) &&
                    GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout))
                {
                    try
                    {
                        TimeSpan shellInactivityTime = Xml.XmlConvert.ToTimeSpan(shellInactivityString);
                        TimeSpan idleTimeoutTime = TimeSpan.FromSeconds(idleTimeout / 1000);

                        if (idleTimeoutTime > shellInactivityTime)
                        {
                            DateTime now = DateTime.Now;
                            disconnectedOn = now.Subtract(shellInactivityTime);
                            expiresOn = disconnectedOn.Value.Add(idleTimeoutTime);

                            return;
                        }
                    }
                    catch (FormatException)
                    { }
                    catch (ArgumentOutOfRangeException)
                    { }
                    catch (OverflowException)
                    { }
                }
            }

            disconnectedOn = null;
            expiresOn = null;
        }

        private static bool GetTimeIntValue(string timeString, out int value)
        {
            if (timeString != null)
            {
                string timeoutString = timeString.Replace("PT", string.Empty).Replace("S", string.Empty);
                try
                {
                    // Convert time from seconds to milliseconds.
                    int idleTimeout = (int)(Convert.ToDouble(timeoutString, CultureInfo.InvariantCulture) * 1000);
                    if (idleTimeout > 0)
                    {
                        value = idleTimeout;
                        return true;
                    }
                }
                catch (FormatException)
                { }
                catch (OverflowException)
                { }
            }

            value = 0;
            return false;
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Set the new runspace pool state based on the state of the
        /// server RunspacePool.
        /// </summary>
        /// <param name="newStateInfo">state information object
        /// describing the state change at the server RunspacePool</param>
        private void SetRunspacePoolState(RunspacePoolStateInfo newStateInfo)
        {
            SetRunspacePoolState(newStateInfo, false);
        }

        /// <summary>
        /// Set the new runspace pool state based on the state of the
        /// server RunspacePool and raise events if required.
        /// </summary>
        /// <param name="newStateInfo">state information object
        /// describing the state change at the server RunspacePool</param>
        /// <param name="raiseEvents">Raise state changed events if true.</param>
        private void SetRunspacePoolState(RunspacePoolStateInfo newStateInfo, bool raiseEvents)
        {
            stateInfo = newStateInfo;

            // Update the availableForConnection variable based on state change.
            AvailableForConnection = (stateInfo.State == RunspacePoolState.Disconnected ||
                                           stateInfo.State == RunspacePoolState.Opened);

            if (raiseEvents)
            {
                RaiseStateChangeEvent(newStateInfo);
            }
        }

        private void HandleSessionDisconnected(object sender, RemoteDataEventArgs<Exception> eventArgs)
        {
            bool stateChange = false;
            lock (this.syncObject)
            {
                if (stateInfo.State == RunspacePoolState.Disconnecting)
                {
                    UpdateDisconnectedExpiresOn();

                    SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Disconnected, eventArgs.Data));
                    stateChange = true;
                }

                // Set boolean indicating this object has previous connection state and so
                // can be reconnected as opposed to the alternative where the connection
                // state has to be reconstructed then connected.
                _canReconnect = true;
            }

            // Do state change work outside of lock.
            if (stateChange)
            {
                RaiseStateChangeEvent(this.stateInfo);
                SetDisconnectAsCompleted();
            }
        }

        private void SetDisconnectAsCompleted()
        {
            if (_disconnectAsyncResult != null && !_disconnectAsyncResult.IsCompleted)
            {
                _disconnectAsyncResult.SetAsCompleted(stateInfo.Reason);
                _disconnectAsyncResult = null;
            }
        }

        private void HandleSessionReconnected(object sender, RemoteDataEventArgs<Exception> eventArgs)
        {
            bool stateChange = false;
            lock (this.syncObject)
            {
                if (stateInfo.State == RunspacePoolState.Connecting)
                {
                    ResetDisconnectedOnExpiresOn();

                    SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Opened, null));
                    stateChange = true;
                }
            }

            // Do state change work outside of lock.
            if (stateChange)
            {
                RaiseStateChangeEvent(this.stateInfo);
                SetReconnectAsCompleted();
            }
        }

        private void SetReconnectAsCompleted()
        {
            if (_reconnectAsyncResult != null && !_reconnectAsyncResult.IsCompleted)
            {
                _reconnectAsyncResult.SetAsCompleted(stateInfo.Reason);
                _reconnectAsyncResult = null;
            }
        }

        /// <summary>
        /// The session is closing set the state and reason accordingly.
        /// </summary>
        /// <param name="sender">Sender of this event, unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleSessionClosing(object sender, RemoteDataEventArgs<Exception> eventArgs)
        {
            // just capture the reason for closing here..handle the session closed event
            // to change state appropriately.
            _closingReason = eventArgs.Data;
        }

        /// <summary>
        /// The session closed, set the state and reason accordingly.
        /// </summary>
        /// <param name="sender">Sender of this event, unused.</param>
        /// <param name="eventArgs">Arguments describing this event.</param>
        private void HandleSessionClosed(object sender, RemoteDataEventArgs<Exception> eventArgs)
        {
            if (eventArgs.Data != null)
            {
                _closingReason = eventArgs.Data;
            }

            // Set state under lock.
            RunspacePoolState prevState;
            RunspacePoolStateInfo finishedStateInfo;
            lock (syncObject)
            {
                prevState = stateInfo.State;

                switch (prevState)
                {
                    case RunspacePoolState.Opening:
                    case RunspacePoolState.Opened:
                    case RunspacePoolState.Disconnecting:
                    case RunspacePoolState.Disconnected:
                    case RunspacePoolState.Connecting:
                        // Since RunspacePool is not in closing state, this close is
                        // happening because of data structure handler error. Set the state to broken.
                        SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Broken, _closingReason));
                        break;

                    case RunspacePoolState.Closing:
                        SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Closed, _closingReason));
                        break;
                }

                finishedStateInfo = new RunspacePoolStateInfo(stateInfo.State, stateInfo.Reason);
            }

            // Raise notification event outside of lock.
            try
            {
                RaiseStateChangeEvent(finishedStateInfo);
            }
            catch (Exception)
            {
                // Don't throw exception on notification thread.
            }

            // Check if we have either an existing disconnect or connect async object
            // and if so make sure they are set to completed since this is a
            // final state for the runspace pool.
            SetDisconnectAsCompleted();
            SetReconnectAsCompleted();

            // Ensure an existing Close async object is completed.
            SetCloseAsCompleted();
        }

        /// <summary>
        /// Set the async result for open as completed.
        /// </summary>
        private void SetOpenAsCompleted()
        {
            RunspacePoolAsyncResult tempOpenAsyncResult = _openAsyncResult;
            _openAsyncResult = null;
            if (tempOpenAsyncResult != null && !tempOpenAsyncResult.IsCompleted)
            {
                tempOpenAsyncResult.SetAsCompleted(stateInfo.Reason);
            }
        }

        /// <summary>
        /// Set the async result for close as completed.
        /// </summary>
        private void SetCloseAsCompleted()
        {
            // abort all pending calls.
            DispatchTable.AbortAllCalls();

            if (_closeAsyncResult != null)
            {
                _closeAsyncResult.SetAsCompleted(stateInfo.Reason);
                _closeAsyncResult = null;
            }

            // Ensure that openAsyncResult is completed and that
            // any error is thrown on the calling thread.
            // The session can be closed at any time, including
            // during Open processing.
            SetOpenAsCompleted();

            // Ensure private application data wait is released.
            try
            {
                _applicationPrivateDataReceived.Set();
            }
            catch (ObjectDisposedException) { }
        }

        /// <summary>
        /// When a response to a SetMaxRunspaces or SetMinRunspaces is received,
        /// from the server, this method sets the response and thereby unblocks
        /// corresponding call.
        /// </summary>
        /// <param name="sender">Sender of this message, unused.</param>
        /// <param name="eventArgs">Contains response and call id.</param>
        private void HandleResponseReceived(object sender, RemoteDataEventArgs<PSObject> eventArgs)
        {
            PSObject data = eventArgs.Data;
            object response = RemotingDecoder.GetPropertyValue<object>(data, RemoteDataNameStrings.RunspacePoolOperationResponse);
            long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId);
            DispatchTable.SetResponse(callId, response);
        }

        /// <summary>
        /// When the client remote session reports a URI redirection, this method will report the
        /// message to the user as a Warning using Host method calls.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs)
        {
            WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo;
            if (wsmanConnectionInfo != null)
            {
                wsmanConnectionInfo.ConnectionUri = eventArgs.Data;
                URIRedirectionReported.SafeInvoke(this, eventArgs);
            }
        }

        /// <summary>
        /// When the server sends a PSEventArgs this method will add it to the local event queue.
        /// </summary>
        private void HandlePSEventArgsReceived(object sender, RemoteDataEventArgs<PSEventArgs> e)
        {
            OnForwardEvent(e.Data);
        }

        /// <summary>
        /// A session disconnect has been initiated by the WinRM robust connection layer.  Set
        /// internal state to Disconnecting.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleSessionRCDisconnecting(object sender, RemoteDataEventArgs<Exception> e)
        {
            Dbg.Assert(this.stateInfo.State == RunspacePoolState.Opened,
                "RC disconnect should only occur for runspace pools in the Opened state.");

            lock (this.syncObject)
            {
                SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Disconnecting, e.Data));
            }

            RaiseStateChangeEvent(this.stateInfo);
        }

        /// <summary>
        /// The session has been successfully created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs eventArgs)
        {
            // Update connectionInfo with updated information from the transport.
            if (eventArgs != null)
            {
                _connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout;
                _connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout;
                WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo;
                if (wsmanConnectionInfo != null)
                {
                    wsmanConnectionInfo.OutputBufferingMode =
                        ((WSManConnectionInfo)eventArgs.ConnectionInfo).OutputBufferingMode;
                }
            }

            // Forward event.
            SessionCreateCompleted.SafeInvoke<CreateCompleteEventArgs>(this, eventArgs);
        }

        private void ResetDisconnectedOnExpiresOn()
        {
            // Reset DisconnectedOn/ExpiresOn
            WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo;
            wsManConnectionInfo?.NullDisconnectedExpiresOn();
        }

        private void UpdateDisconnectedExpiresOn()
        {
            // Set DisconnectedOn/ExpiresOn for disconnected session.
            WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo;
            wsManConnectionInfo?.SetDisconnectedExpiresOnToNow();
        }

        /// <summary>
        /// Waits for application private data from server before raising
        /// event:  Connecting->Opened state changed event.
        /// </summary>
        /// <param name="state"></param>
        private void WaitAndRaiseConnectEventsProc(object state)
        {
            RunspacePoolStateInfo info = state as RunspacePoolStateInfo;
            Dbg.Assert(info != null, "State -> Event arguments cannot be null.");

            // Wait for private application data to arrive from server.
            try
            {
                _applicationPrivateDataReceived.WaitOne();
            }
            catch (ObjectDisposedException) { }

            // Raise state changed event.
            try
            {
                RaiseStateChangeEvent(info);
            }
            catch (Exception)
            {
            }

            // Set Opened async object.
            SetOpenAsCompleted();
        }

        #endregion Private Methods

        #region Private Members

        private readonly RunspaceConnectionInfo _connectionInfo;     // connection info with which this
        // runspace is created
        // data structure handler handling
        private RunspacePoolAsyncResult _openAsyncResult; // async result object generated on
        // CoreOpen
        private RunspacePoolAsyncResult _closeAsyncResult; // async result object generated by
        // BeginClose
        private Exception _closingReason;                       // reason for a Closing state transition
        private RunspacePoolAsyncResult _disconnectAsyncResult; // async result object generated on CoreDisconnect
        private RunspacePoolAsyncResult _reconnectAsyncResult;  // async result object generated on CoreReconnect
        private bool _isDisposed;

        private DispatchTable<object> DispatchTable { get; }

        private bool _canReconnect;
        private string _friendlyName = string.Empty;

        private readonly System.Collections.Concurrent.ConcurrentStack<PowerShell> _runningPowerShells;

        #endregion Private Members

        #region IDisposable

        /// <summary>
        /// Release all resources.
        /// </summary>
        /// <param name="disposing">If true, release all managed resources.</param>
        protected override void Dispose(bool disposing)
        {
            // dispose the base class before disposing dataStructure handler.
            base.Dispose(disposing);
            if (!_isDisposed)
            {
                _isDisposed = true;
                DataStructureHandler.Dispose(disposing);
                _applicationPrivateDataReceived.Dispose();
            }
        }

        #endregion IDisposable
    }

    #region ConnectCommandInfo class

    /// <summary>
    /// Class defining a remote command to connect to.
    /// </summary>
    internal class ConnectCommandInfo
    {
        /// <summary>
        /// Remote command instance Id.
        /// </summary>
        public Guid CommandId { get; } = Guid.Empty;

        /// <summary>
        /// Remote command string.
        /// </summary>
        public string Command { get; } = string.Empty;

        /// <summary>
        /// Constructs a remote command object.
        /// </summary>
        /// <param name="cmdId">Command instance Id.</param>
        /// <param name="cmdStr">Command string.</param>
        public ConnectCommandInfo(Guid cmdId, string cmdStr)
        {
            CommandId = cmdId;
            Command = cmdStr;
        }
    }

    #endregion

    #region RemoteRunspacePoolEnumeration class

    /// <summary>
    /// Enumerates remote runspacepools (Shells) and running commands
    /// using Get-WSManInstance cmdlet.
    /// </summary>
    internal static class RemoteRunspacePoolEnumeration
    {
        /// <summary>
        /// Gets an array of XmlElement objects representing all
        /// disconnected runspace pools on the indicated server.
        /// </summary>
        /// <param name="wsmanConnectionInfo">Specifies the remote server to connect to.</param>]
        /// <returns>Collection of XmlElement objects.</returns>
        internal static Collection<PSObject> GetRemotePools(WSManConnectionInfo wsmanConnectionInfo)
        {
            Collection<PSObject> result;
            using (PowerShell powerShell = PowerShell.Create())
            {
                // Enumerate remote runspaces using the Get-WSManInstance cmdlet.
                powerShell.AddCommand("Get-WSManInstance");

                // Add parameters to enumerate Shells (runspace pools).
                powerShell.AddParameter("ResourceURI", "Shell");
                powerShell.AddParameter("Enumerate", true);

                // Add parameters for server connection.
                powerShell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName);
                powerShell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism));
                if (wsmanConnectionInfo.Credential != null)
                {
                    powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential);
                }

                if (wsmanConnectionInfo.CertificateThumbprint != null)
                {
                    powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint);
                }

                if (wsmanConnectionInfo.PortSetting != -1)
                {
                    powerShell.AddParameter("Port", wsmanConnectionInfo.Port);
                }

                if (CheckForSSL(wsmanConnectionInfo))
                {
                    powerShell.AddParameter("UseSSL", true);
                }

                if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName))
                {
                    // Remove prepended path character.
                    string appName = wsmanConnectionInfo.AppName.TrimStart('/');
                    powerShell.AddParameter("ApplicationName", appName);
                }

                powerShell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo));

                result = powerShell.Invoke();
            }

            return result;
        }

        /// <summary>
        /// Gets an array of XmlElement objects representing each running command
        /// on the specified runspace pool with the shellid Guid.
        /// </summary>
        /// <param name="shellId">Guid of shellId (runspacepool Id).</param>
        /// <param name="wsmanConnectionInfo">Specifies the remote server to connect to.</param>]
        /// <returns>Collection of XmlElement objects.</returns>
        internal static Collection<PSObject> GetRemoteCommands(Guid shellId, WSManConnectionInfo wsmanConnectionInfo)
        {
            Collection<PSObject> result;
            using (PowerShell powerShell = PowerShell.Create())
            {
                // Enumerate remote runspace commands using the Get-WSManInstance cmdlet.
                powerShell.AddCommand("Get-WSManInstance");

                // Add parameters to enumerate commands.
                string filterStr = string.Create(CultureInfo.InvariantCulture, $"ShellId='{shellId.ToString().ToUpperInvariant()}'");
                powerShell.AddParameter("ResourceURI", @"Shell/Command");
                powerShell.AddParameter("Enumerate", true);
                powerShell.AddParameter("Dialect", "Selector");
                powerShell.AddParameter("Filter", filterStr);

                // Add parameters for server connection.
                powerShell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName);
                powerShell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism));
                if (wsmanConnectionInfo.Credential != null)
                {
                    powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential);
                }

                if (wsmanConnectionInfo.CertificateThumbprint != null)
                {
                    powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint);
                }

                if (wsmanConnectionInfo.PortSetting != -1)
                {
                    powerShell.AddParameter("Port", wsmanConnectionInfo.Port);
                }

                if (CheckForSSL(wsmanConnectionInfo))
                {
                    powerShell.AddParameter("UseSSL", true);
                }

                if (!string.IsNullOrEmpty(wsmanConnectionInfo.AppName))
                {
                    // Remove prepended path character.
                    string appName = wsmanConnectionInfo.AppName.TrimStart('/');
                    powerShell.AddParameter("ApplicationName", appName);
                }

                powerShell.AddParameter("SessionOption", GetSessionOptions(wsmanConnectionInfo));

                result = powerShell.Invoke();
            }

            return result;
        }

        /// <summary>
        /// Use the WSMan New-WSManSessionOption cmdlet to create a session options
        /// object used for Get-WSManInstance queries.
        /// </summary>
        /// <param name="wsmanConnectionInfo">WSManConnectionInfo.</param>
        /// <returns>WSMan session options object.</returns>
        private static object GetSessionOptions(WSManConnectionInfo wsmanConnectionInfo)
        {
            Collection<PSObject> result;
            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddCommand("New-WSManSessionOption");

                if (wsmanConnectionInfo.ProxyAccessType != ProxyAccessType.None)
                {
                    powerShell.AddParameter("ProxyAccessType", "Proxy" + wsmanConnectionInfo.ProxyAccessType.ToString());
                    powerShell.AddParameter("ProxyAuthentication", wsmanConnectionInfo.ProxyAuthentication.ToString());

                    if (wsmanConnectionInfo.ProxyCredential != null)
                    {
                        powerShell.AddParameter("ProxyCredential", wsmanConnectionInfo.ProxyCredential);
                    }
                }

                // New-WSManSessionOption uses the SPNPort number here to enable SPN
                // server authentication.  It looks like any value > 0 will enable
                // this.  Since the Port property always returns a valid port value (>0)
                // just pass the WSManConnectionInfo port parameter.
                if (wsmanConnectionInfo.IncludePortInSPN)
                {
                    powerShell.AddParameter("SPNPort", wsmanConnectionInfo.Port);
                }

                powerShell.AddParameter("SkipCACheck", wsmanConnectionInfo.SkipCACheck);
                powerShell.AddParameter("SkipCNCheck", wsmanConnectionInfo.SkipCNCheck);
                powerShell.AddParameter("SkipRevocationCheck", wsmanConnectionInfo.SkipRevocationCheck);

                powerShell.AddParameter("OperationTimeout", wsmanConnectionInfo.OperationTimeout);
                powerShell.AddParameter("NoEncryption", wsmanConnectionInfo.NoEncryption);
                powerShell.AddParameter("UseUTF16", wsmanConnectionInfo.UseUTF16);

                result = powerShell.Invoke();
            }

            return result[0].BaseObject;
        }

        private static bool CheckForSSL(WSManConnectionInfo wsmanConnectionInfo)
        {
            return (!string.IsNullOrEmpty(wsmanConnectionInfo.Scheme) &&
                    wsmanConnectionInfo.Scheme.Contains(WSManConnectionInfo.HttpsScheme, StringComparison.OrdinalIgnoreCase));
        }

        private static int ConvertPSAuthToWSManAuth(AuthenticationMechanism psAuth)
        {
            int wsmanAuth;

            switch (psAuth)
            {
                case AuthenticationMechanism.Default:
                    wsmanAuth = 0x1;
                    break;

                case AuthenticationMechanism.Basic:
                    wsmanAuth = 0x8;
                    break;

                case AuthenticationMechanism.Digest:
                    wsmanAuth = 0x2;
                    break;

                case AuthenticationMechanism.Credssp:
                    wsmanAuth = 0x80;
                    break;

                case AuthenticationMechanism.Kerberos:
                    wsmanAuth = 0x10;
                    break;

                case AuthenticationMechanism.Negotiate:
                    wsmanAuth = 0x4;
                    break;

                default:
                    wsmanAuth = 0x1;
                    break;
            }

            return wsmanAuth;
        }
    }

    #endregion
}