File size: 68,362 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace System.Management.Automation.Internal
{
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
/// <summary>
/// Base class representing a FIFO memory based object stream.
/// The purpose of this abstraction is to provide the
/// semantics of a unidirectional stream of objects
/// between two threads using a dynamic memory buffer.
/// </summary>
internal abstract class ObjectStreamBase : IDisposable
{
#region Public events
/// <summary>
/// Event fired when data is added to the buffer.
/// </summary>
internal event EventHandler DataReady = null;
/// <summary>
/// Raises DataReadyEvent.
/// </summary>
/// <param name="source">
/// Source of the event
/// </param>
/// <param name="args">
/// Event args
/// </param>
internal void FireDataReadyEvent(object source, EventArgs args)
{
DataReady.SafeInvoke(source, args);
}
#endregion Public events
#region Virtual Properties
/// <summary>
/// Get the capacity of the stream.
/// </summary>
/// <value>
/// The capacity of the stream.
/// </value>
/// <remarks>
/// The capacity is the number of objects the stream may contain at one time. Once this
/// limit is reached, attempts to write into the stream block until buffer space
/// becomes available.
/// MaxCapacity cannot change, so we can skip the lock.
/// </remarks>
internal abstract int MaxCapacity { get; }
/// <summary>
/// Waitable handle for callers to wait on until data ready to read.
/// </summary>
/// <remarks>
/// The handle is set when data becomes available to read or
/// when a partial read has completed. If multiple readers
/// are used, setting the handle does not guarantee that
/// a read operation will return data. If using multiple
/// reader threads, <see cref="NonBlockingRead"/> for
/// performing non-blocking reads.
/// </remarks>
internal virtual WaitHandle ReadHandle
{
get
{
#pragma warning disable 56503
// disabled compiler warning as PSDataCollectionStream doesn't override this
// and I didn't want code duplication.
throw PSTraceSource.NewNotSupportedException();
#pragma warning restore 56503
}
}
/// <summary>
/// Waitable handle for callers to block until buffer space becomes available.
/// </summary>
/// <remarks>
/// The handle is set when space becomes available for writing. For multiple
/// writer threads writing to a bounded stream, the writer may still block
/// if another thread fills the stream to capacity.
/// </remarks>
internal virtual WaitHandle WriteHandle
{
get
{
#pragma warning disable 56503
// disabled compiler warning as PSDataCollectionStream doesn't override this
// and I didn't want code duplication.
throw PSTraceSource.NewNotSupportedException();
#pragma warning restore 56503
}
}
/// <summary>
/// Determine if we are at the end of the stream.
/// </summary>
/// <remarks>
/// EndOfPipeline is defined as the stream being closed and containing
/// zero objects. Readers check this to determine if any objects
/// are in the stream. Writers should check <see cref="IsOpen"/> to determine
/// if the stream can be written to.
/// </remarks>
internal abstract bool EndOfPipeline { get; }
/// <summary>
/// Check if the stream is open for further writes.
/// </summary>
/// <returns>True if the stream is open, false if not.</returns>
/// <remarks>
/// IsOpen returns true until the first call to Close(). Writers should
/// check IsOpen to determine if a write operation can be made. Note that
/// writers need to catch <see cref="PipelineClosedException"/>.
/// <seealso cref="EndOfPipeline"/>
/// </remarks>
internal abstract bool IsOpen { get; }
/// <summary>
/// Returns the number of objects in the stream.
/// </summary>
internal abstract int Count { get; }
/// <summary>
/// Return a PipelineReader(object) for this stream.
/// </summary>
internal abstract PipelineReader<object> ObjectReader { get; }
/// <summary>
/// Return a PipelineReader(PSObject) for this stream.
/// </summary>
internal abstract PipelineReader<PSObject> PSObjectReader { get; }
// 913921-2005/07/08 ObjectWriter can be retrieved on a closed stream
/// <summary>
/// Return an PipelineWriter for this stream.
/// </summary>
internal abstract PipelineWriter ObjectWriter { get; }
#endregion
#region Read Abstractions
/// <summary>
/// Read a single object from the stream.
/// </summary>
/// <returns>The next object in the stream or AutomationNull if EndOfPipeline is reached.</returns>
/// <remarks>This method blocks if the stream is empty</remarks>
internal virtual object Read()
{
throw PSTraceSource.NewNotSupportedException();
}
/// <summary>
/// Read at most <paramref name="count"/> objects.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count"/> is less than 0
/// </exception>
/// <remarks>
/// This method blocks if the number of objects in the stream is less than <paramref name="count"/>
/// and the stream is not closed.
///
/// If there are multiple reader threads, the objects returned
/// to blocking reads Read(int count) and ReadToEnd()
/// are not necessarily single blocks of objects added to the
/// stream in that order. For example, if ABCDEF are added to the
/// stream, one reader may get ABDE and the other may get CF.
/// Each reader reads items from the stream as they become available.
/// Otherwise, if a maximum _capacity has been imposed, the writer
/// and reader could become mutually deadlocked.
///
/// When there are multiple blocked readers, any of the readers
/// may get the next object(s) added.
/// </remarks>
internal virtual Collection<object> Read(int count)
{
throw PSTraceSource.NewNotSupportedException();
}
/// <summary>
/// Blocks until the pipeline closes and reads all objects.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// If the stream is empty, a collection of size zero is returned.
///
/// If there are multiple reader threads, the objects returned
/// to blocking reads Read(int count) and ReadToEnd()
/// are not necessarily single blocks of objects added to the
/// stream in that order. For example, if ABCDEF are added to the
/// stream, one reader may get ABDE and the other may get CF.
/// Each reader reads items from the stream as they become available.
/// Otherwise, if a maximum _capacity has been imposed, the writer
/// and reader could become mutually deadlocked.
///
/// When there are multiple blocked readers, any of the readers
/// may get the next object(s) added.
/// </remarks>
internal virtual Collection<object> ReadToEnd()
{
throw PSTraceSource.NewNotSupportedException();
}
/// <summary>
/// Reads objects currently in the stream, but does not block.
/// </summary>
/// <returns>An array of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty array is returned.
/// </remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="maxRequested"/> is less than 0
/// </exception>
internal virtual Collection<object> NonBlockingRead(int maxRequested)
{
throw PSTraceSource.NewNotSupportedException();
}
/// <summary>
/// Peek the next object.
/// </summary>
/// <returns>
/// The next object in the stream or AutomationNull.Value if the stream is empty
/// </returns>
/// <exception cref="PipelineClosedException">The ObjectStream is closed.</exception>
internal virtual object Peek()
{
throw PSTraceSource.NewNotSupportedException();
}
#endregion
#region Write Abstractions
/// <summary>
/// Writes a object to the current position in the stream and
/// advances the position within the stream by one object.
/// </summary>
/// <param name="value">The object to write to the stream.</param>
/// <returns>
/// One, if the write was successful, otherwise;
/// zero if the stream was closed before the object could be written,
/// or if the object was AutomationNull.Value.
/// </returns>
/// <exception cref="PipelineClosedException">
/// The stream is closed
/// </exception>
/// <remarks>
/// AutomationNull.Value is ignored
/// </remarks>
internal virtual int Write(object value)
{
return Write(value, false);
}
/// <summary>
/// Write objects to the underlying stream.
/// </summary>
/// <param name="obj">Object or enumeration to read from.</param>
/// <param name="enumerateCollection">
/// If enumerateCollection is true, and <paramref name="obj"/>
/// is an enumeration according to LanguagePrimitives.GetEnumerable,
/// the objects in the enumeration will be unrolled and
/// written separately. Otherwise, <paramref name="obj"/>
/// will be written as a single object.
/// </param>
/// <returns>The number of objects written.</returns>
/// <exception cref="PipelineClosedException">
/// The underlying stream is closed
/// </exception>
/// <remarks>
/// If the enumeration contains elements equal to
/// AutomationNull.Value, they are ignored.
/// This can cause the return value to be less than the size of
/// the collection.
/// </remarks>
internal virtual int Write(object obj, bool enumerateCollection)
{
throw PSTraceSource.NewNotSupportedException();
}
#endregion
#region Close / Flush
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// Causes subsequent calls to IsOpen to return false and calls to
/// a write operation to throw PipelineClosedException.
/// All calls to Close() after the first call are silently ignored.
/// </remarks>
internal virtual void Close()
{
throw PSTraceSource.NewNotSupportedException();
}
/// <summary>
/// Flush the data from the stream. Closed streams may be flushed.
/// </summary>
internal virtual void Flush()
{
throw PSTraceSource.NewNotSupportedException();
}
#endregion
#region IDisposable
/// <summary>
/// Public method for dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected abstract void Dispose(bool disposing);
#endregion IDisposable
}
/// <summary>
/// A FIFO memory based object stream.
/// The purpose of this stream class is to provide the
/// semantics of a unidirectional stream of objects
/// between two threads using a dynamic memory buffer.
/// </summary>
/// <remarks>
/// The stream may be bound or unbounded. Bounded streams
/// are created via passing a capacity to the constructor.
/// Unbounded streams are created using the default constructor.
///
/// The capacity of the stream can not be changed after
/// construction.
///
/// For bounded streams, attempts to write to the stream when
/// the capacity has been reached causes the writer to block
/// until objects are read.
///
/// For unbounded streams, writers only block for the amount
/// of time needed to acquire exclusive access to the
/// stream. Note that unbounded streams have a capacity of
/// of Int32.MaxValue objects. In theory, if this limit were
/// reached, the stream would function as a bounded stream.
///
/// This class is safe for multi-threaded use with the following
/// side-effects:
///
/// > For bounded streams, write operations are not guaranteed to
/// be atomic. If a write operation causes the capacity to be
/// reached without writing all data, a partial write occurs and
/// the writer blocks until data is read from the stream.
///
/// > When multiple writer or reader threads are used, the order
/// the reader or writer acquires a lock on the stream is
/// undefined. This means that the first call to write does not
/// guarantee the writer will acquire a write lock first. The first
/// call to read does not guarantee the reader will acquire the
/// read lock first.
///
/// > Reads and writes may occur in any order. With a bounded
/// stream, write operations between threads may also result in
/// interleaved write operations.
///
/// The result is that the order of data is only guaranteed if there is a
/// single writer.
/// </remarks>
// 897230-2003/10/29-JonN marked sealed
// 905990-2005/05/10-JonN Removed IDisposable
internal sealed class ObjectStream : ObjectStreamBase, IDisposable
{
#region Private Fields
/// <summary>
/// Objects in the stream.
/// </summary>
// PERF-2003/08/22-JonN We should probably use Queue instead
// PERF-2004/06/30-JonN Probably more efficient to use type
// Collection<object> as the underlying store
private readonly List<object> _objects;
/// <summary>
/// Is the stream open or closed for writing?
/// </summary>
private bool _isOpen;
#region Synchronization handles
/// <summary>
/// Read handle - signaled when data is ready to read.
/// </summary>
/// <remarks>
/// This event may, on occasion, be signalled even when there is
/// no data available. If this happens, just wait again.
/// Never wait on this event alone. Since this is an AutoResetEvent,
/// there is no way to definitely release all blocked threads when
/// the stream is closed for reading. Instead, use WaitAny on
/// this handle and also _readClosedHandle.
/// </remarks>
private readonly AutoResetEvent _readHandle;
/// <summary>
/// Handle returned to callers for blocking on data ready.
/// </summary>
private ManualResetEvent _readWaitHandle;
/// <summary>
/// When this handle is set, the stream is closed for reading,
/// so all blocked readers should be released.
/// </summary>
private readonly ManualResetEvent _readClosedHandle;
/// <summary>
/// Write handle - signaled with the number of objects in the
/// stream becomes less than the maximum number of objects
/// allowed in the stream. <see cref="_capacity"/>
/// </summary>
/// <remarks>
/// This event may, on occasion, be signalled even when there is
/// no write buffer available. If this happens, just wait again.
/// Never wait on this event alone. Since this is an AutoResetEvent,
/// there is no way to definitely release all blocked threads when
/// the stream is closed for writing. Instead, use WaitAny on
/// this handle and also _writeClosedHandle.
/// </remarks>
private readonly AutoResetEvent _writeHandle;
/// <summary>
/// Handle returned to callers for blocking until buffer space
/// is available for write.
/// </summary>
private ManualResetEvent _writeWaitHandle;
/// <summary>
/// When this handle is set, the stream is closed for writing,
/// so all blocked readers should be released.
/// </summary>
private readonly ManualResetEvent _writeClosedHandle;
#endregion Synchronization handles
/// <summary>
/// The object reader for this stream.
/// </summary>
/// <remarks>
/// This field is allocated on first demand and
/// returned on subsequent calls.
/// </remarks>
private PipelineReader<object> _reader = null;
/// <summary>
/// The PSObject reader for this stream.
/// </summary>
/// <remarks>
/// This field is allocated on first demand and
/// returned on subsequent calls.
/// </remarks>
private PipelineReader<PSObject> _mshreader = null;
/// <summary>
/// The object writer for this stream.
/// </summary>
/// <remarks>
/// This field is allocated on first demand and
/// returned on subsequent calls.
/// </remarks>
private PipelineWriter _writer = null;
/// <summary>
/// Maximum number of objects allowed in the stream
/// Note that this is not permitted to be more than Int32.MaxValue,
/// since the underlying list has this limitation.
/// </summary>
private readonly int _capacity = Int32.MaxValue;
/// <summary>
/// This object is used to acquire an exclusive lock on the stream.
/// </summary>
/// <remarks>
/// Note that we lock _monitorObject rather than "this" so that
/// we are protected from outside code interfering in our
/// critical section. Thanks to Wintellect for the hint.
/// </remarks>
private readonly object _monitorObject = new object();
/// <summary>
/// Indicates if this stream has already been disposed.
/// </summary>
private bool _disposed = false;
#endregion Private Fields
#region Ctor
/// <summary>
/// Default constructor.
/// </summary>
/// <remarks>
/// Constructs a stream with a maximum size of Int32.Max
/// </remarks>
internal ObjectStream()
: this(Int32.MaxValue)
{
}
/// <summary>
/// Allocate the stream with an initial size.
/// </summary>
/// <param name="capacity">
/// The maximum number of objects to allow in the buffer at a time.
/// Note that this is not permitted to be more than Int32.MaxValue,
/// since the underlying list has this limitation
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="_capacity"/> is less than or equal to zero
/// <paramref name="_capacity"/> is greater than Int32.MaxValue
/// </exception>
internal ObjectStream(int capacity)
{
if (capacity <= 0 || capacity > Int32.MaxValue)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(capacity), capacity);
}
// the maximum number of objects to allow in the stream at a given time.
_capacity = capacity;
// event is not signaled since there is no data to read
_readHandle = new AutoResetEvent(false);
// event is signaled since there is available buffer space
_writeHandle = new AutoResetEvent(true);
// event is not signaled since the thread is still readable
_readClosedHandle = new ManualResetEvent(false);
// event is signaled since the thread is still writeable
_writeClosedHandle = new ManualResetEvent(false);
// the FIFO set of objects in the stream
_objects = new List<object>();
// Is the stream open?
_isOpen = true;
}
#endregion Ctor
#region internal properties
/// <summary>
/// Get the capacity of the stream.
/// </summary>
/// <value>
/// The capacity of the stream.
/// </value>
/// <remarks>
/// The capacity is the number of objects the stream may contain at one time. Once this
/// limit is reached, attempts to write into the stream block until buffer space
/// becomes available.
/// MaxCapacity cannot change, so we can skip the lock.
/// </remarks>
internal override int MaxCapacity
{
get
{
return _capacity;
}
}
/// <summary>
/// Waitable handle for callers to wait on until data ready to read.
/// </summary>
/// <remarks>
/// The handle is set when data becomes available to read or
/// when a partial read has completed. If multiple readers
/// are used, setting the handle does not guarantee that
/// a read operation will return data. If using multiple
/// reader threads, <see cref="NonBlockingRead"/> for
/// performing non-blocking reads.
/// </remarks>
internal override WaitHandle ReadHandle
{
get
{
WaitHandle handle = null;
lock (_monitorObject)
{
// Create the handle signaled if there are objects in the stream
// or the stream has been closed. The closed scenario addresses
// Pipeline readers that execute asynchronously. Since the pipeline
// may complete with zero objects before the caller objects this
// handle, it will block indefinitely unless it is set.
_readWaitHandle ??= new ManualResetEvent(_objects.Count > 0 || !_isOpen);
handle = _readWaitHandle;
}
return handle;
}
}
/// <summary>
/// Waitable handle for callers to block until buffer space becomes available.
/// </summary>
/// <remarks>
/// The handle is set when space becomes available for writing. For multiple
/// writer threads writing to a bounded stream, the writer may still block
/// if another thread fills the stream to capacity.
/// </remarks>
internal override WaitHandle WriteHandle
{
get
{
WaitHandle handle = null;
lock (_monitorObject)
{
_writeWaitHandle ??= new ManualResetEvent(_objects.Count < _capacity || !_isOpen);
handle = _writeWaitHandle;
}
return handle;
}
}
/// <summary>
/// Return a PipelineReader(object) for this stream.
/// </summary>
internal override PipelineReader<object> ObjectReader
{
get
{
PipelineReader<object> reader = null;
lock (_monitorObject)
{
// Always return an object reader, even if the stream
// is closed. This is to address requesting the object reader
// after calling Pipeline.Execute(). NOTE: If Execute completes
// without writing data to the output queue, the
// stream will be in the EndOfPipeline state because the
// stream is closed and has zero data. Since this is a valid
// and expected execution path, we don't want to throw an exception.
_reader ??= new ObjectReader(this);
reader = _reader;
}
return reader;
}
}
/// <summary>
/// Return a PipelineReader(PSObject) for this stream.
/// </summary>
internal override PipelineReader<PSObject> PSObjectReader
{
get
{
PipelineReader<PSObject> reader = null;
lock (_monitorObject)
{
// Always return an object reader, even if the stream
// is closed. This is to address requesting the object reader
// after calling Pipeline.Execute(). NOTE: If Execute completes
// without writing data to the output queue, the
// stream will be in the EndOfPipeline state because the
// stream is closed and has zero data. Since this is a valid
// and expected execution path, we don't want to throw an exception.
_mshreader ??= new PSObjectReader(this);
reader = _mshreader;
}
return reader;
}
}
// 913921-2005/07/08 ObjectWriter can be retrieved on a closed stream
/// <summary>
/// Return an PipelineWriter for this stream.
/// </summary>
internal override PipelineWriter ObjectWriter
{
get
{
PipelineWriter writer = null;
lock (_monitorObject)
{
_writer ??= new ObjectWriter(this) as PipelineWriter;
writer = _writer;
}
return writer;
}
}
/// <summary>
/// Determine if we are at the end of the stream.
/// </summary>
/// <remarks>
/// EndOfPipeline is defined as the stream being closed and containing
/// zero objects. Readers check this to determine if any objects
/// are in the stream. Writers should check <see cref="IsOpen"/> to determine
/// if the stream can be written to.
/// </remarks>
internal override bool EndOfPipeline
{
get
{
bool endOfStream = true;
lock (_monitorObject)
{
endOfStream = (_objects.Count == 0 && !_isOpen);
}
return endOfStream;
}
}
/// <summary>
/// Check if the stream is open for further writes.
/// </summary>
/// <returns>True if the stream is open, false if not.</returns>
/// <remarks>
/// IsOpen returns true until the first call to Close(). Writers should
/// check IsOpen to determine if a write operation can be made. Note that
/// writers need to catch <see cref="PipelineClosedException"/>.
/// <seealso cref="EndOfPipeline"/>
/// </remarks>
internal override bool IsOpen
{
get
{
bool isOpen = true;
// 2003/09/02-JonN Hitesh says that the access
// of a bool variable is atomic so there is no need
// for the lock.
lock (_monitorObject)
{
isOpen = _isOpen;
}
return isOpen;
}
}
/// <summary>
/// Returns the number of objects in the stream.
/// </summary>
internal override int Count
{
get
{
int count = 0;
lock (_monitorObject)
{
count = _objects.Count;
}
return count;
}
}
#endregion internal properties
#region private locking code
/// <summary>
/// Wait for data to be readable.
/// </summary>
/// <returns>True if EndOfPipeline is not reached.</returns>
/// <remarks>
/// WaitRead does not guarantee that data is present in the stream,
/// only that data was added when the event was signaled. Since there may be
/// multiple readers, data may be removed from the stream
/// before the caller has a chance to read the data.
/// This method should never be called within a lock(_monitorObject).
/// </remarks>
private bool WaitRead()
{
if (!EndOfPipeline)
{
try
{
WaitHandle[] ha = { _readHandle, _readClosedHandle };
WaitHandle.WaitAny(ha); // ignore return value
}
catch (ObjectDisposedException)
{
// Since the _readHandle must be acquired outside
// a lock there's a chance that it was
// disposed after checking EndOfPipeline
}
}
return !EndOfPipeline;
}
/// <summary>
/// Wait for data to be writeable.
/// </summary>
/// <returns>True if the stream is writeable, otherwise; false.</returns>
/// <remarks>
/// WaitWrite does not guarantee that buffer space will be available in the stream
/// when the caller attempts to write, only that buffer space was available
/// when the event was signaled.
/// This method should never be called within a lock(_monitorObject).
/// </remarks>
private bool WaitWrite()
{
if (IsOpen)
{
try
{
WaitHandle[] ha = { _writeHandle, _writeClosedHandle };
WaitHandle.WaitAny(ha); // ignore return value
}
catch (ObjectDisposedException)
{
// Since the _writeHandle must be acquired outside
// a lock there's a chance that it was
// disposed after checking IsOpen
}
}
return IsOpen;
}
/// <summary>
/// Utility method to signal handles and raise events
/// in the consistent order.
/// NOTE: Release the lock before raising events; otherwise,
/// there is a possible deadlock during the readable event.
/// </summary>
/// <remarks>
/// RaiseEvents is fairly idempotent, although it will signal
/// DataReady every time.
/// </remarks>
private void RaiseEvents()
{
bool unblockReaders = true;
bool unblockWriters = true;
bool endOfStream = false;
try
{
lock (_monitorObject)
{
// External readers block only for open streams
// with no stored objects. External writers block
// only for open streams with no free buffer space.
unblockReaders = (!_isOpen || (_objects.Count > 0));
unblockWriters = (!_isOpen || (_objects.Count < _capacity));
endOfStream = (!_isOpen && (_objects.Count == 0));
// I would prefer to set the ManualResetEvents outside
// of the lock, so that the unblocked thread would not
// immediately be re-blocked. However, I am not
// confident that multiple sets/resets might not get
// out of order and leave the handle in the wrong state.
if (_readWaitHandle != null)
{
try
{
if (unblockReaders)
{
_readWaitHandle.Set();
}
else
{
_readWaitHandle.Reset();
}
}
catch (ObjectDisposedException)
{
}
}
if (_writeWaitHandle != null)
{
try
{
if (unblockWriters)
{
_writeWaitHandle.Set();
}
else
{
_writeWaitHandle.Reset();
}
}
catch (ObjectDisposedException)
{
}
}
}
}
finally
{
// We prefer to set the AutoResetEvents outside of the lock,
// so that the unblocked thread will not immediately be
// re-blocked. This works because setting the handle
// is idempotent.
if (unblockReaders)
{
try
{
_readHandle.Set();
}
catch (ObjectDisposedException)
{
}
}
if (unblockWriters)
{
try
{
_writeHandle.Set();
}
catch (ObjectDisposedException)
{
}
}
if (endOfStream)
{
try
{
_readClosedHandle.Set();
}
catch (ObjectDisposedException)
{
}
}
}
// This causes a synchronous call to the
// client-provided handler.
if (unblockReaders)
{
FireDataReadyEvent(this, EventArgs.Empty);
}
#if (false)
//
// NOTE: Event delegates are called only after the internal
// AutoResetEvents are set to ensure that an exception in an
// event delegate does not leave the reset events in a bad
// state.
if (unblockWriters && WriteReady != null)
{
WriteReady (this, new EventArgs ());
}
#endif
}
#endregion private locking code
#region internal methods
/// <summary>
/// Flush the data from the stream. Closed streams may be flushed.
/// </summary>
internal override void Flush()
{
bool raiseEvents = false;
try
{
lock (_monitorObject)
{
if (_objects.Count > 0)
{
raiseEvents = true;
_objects.Clear();
}
}
}
finally
{
if (raiseEvents)
{
RaiseEvents();
}
}
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// Causes subsequent calls to IsOpen to return false and calls to
/// a write operation to throw PipelineClosedException.
/// All calls to Close() after the first call are silently ignored.
/// </remarks>
internal override void Close()
{
bool raiseEvents = false;
try
{
lock (_monitorObject)
{
// if we transition from open to closed,
// signal any blocking readers or writers
// to ensure the close is seen.
if (_isOpen)
{
raiseEvents = true;
_isOpen = false;
}
}
}
finally
{
if (raiseEvents)
{
// RaiseEvents does not manage _writeClosedHandle
try
{
_writeClosedHandle.Set();
}
catch (ObjectDisposedException)
{
}
RaiseEvents();
}
}
}
#endregion internal methods
#region Read Methods
/// <summary>
/// Read a single object from the stream.
/// </summary>
/// <returns>The next object in the stream or AutomationNull if EndOfPipeline is reached.</returns>
/// <remarks>This method blocks if the stream is empty</remarks>
internal override object Read()
{
Collection<object> result = Read(1);
if (result.Count == 1)
{
return result[0];
}
Diagnostics.Assert(result.Count == 0, "Invalid number of objects returned");
return AutomationNull.Value;
}
/// <summary>
/// Read at most <paramref name="count"/> objects.
/// </summary>
/// <param name="count">The maximum number of objects to read.</param>
/// <returns>The objects read.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count"/> is less than 0
/// </exception>
/// <remarks>
/// This method blocks if the number of objects in the stream is less than <paramref name="count"/>
/// and the stream is not closed.
///
/// If there are multiple reader threads, the objects returned
/// to blocking reads Read(int count) and ReadToEnd()
/// are not necessarily single blocks of objects added to the
/// stream in that order. For example, if ABCDEF are added to the
/// stream, one reader may get ABDE and the other may get CF.
/// Each reader reads items from the stream as they become available.
/// Otherwise, if a maximum _capacity has been imposed, the writer
/// and reader could become mutually deadlocked.
///
/// When there are multiple blocked readers, any of the readers
/// may get the next object(s) added.
/// </remarks>
internal override Collection<object> Read(int count)
{
if (count < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count);
}
if (count == 0)
{
return new Collection<object>();
}
Collection<object> results = new Collection<object>();
bool raiseEvents = false;
while ((count > 0) && WaitRead())
{
try
{
lock (_monitorObject)
{
// double check to ensure data is ready
if (_objects.Count == 0)
{
continue; // wait some more
}
raiseEvents = true;
// NTRAID#Windows Out Of Band Releases-925566-2005/12/07-JonN
int objectsAdded = 0;
foreach (object o in _objects)
{
results.Add(o);
objectsAdded++;
if (--count <= 0)
break;
}
_objects.RemoveRange(0, objectsAdded);
}
}
finally
{
// Raise the appropriate read/write events outside the lock. This is
// inside the while loop to ensure writers can have a chance to
// write otherwise the reader will starve.
// NOTE: This must occur in the finally block to ensure
// the AutoResetEvents are left in the appropriate state, even
// for error paths.
if (raiseEvents)
{
RaiseEvents();
}
}
}
return results;
}
/// <summary>
/// Blocks until the pipeline closes and reads all objects.
/// </summary>
/// <returns>A collection of zero or more objects.</returns>
/// <remarks>
/// If the stream is empty, a collection of size zero is returned.
///
/// If there are multiple reader threads, the objects returned
/// to blocking reads Read(int count) and ReadToEnd()
/// are not necessarily single blocks of objects added to the
/// stream in that order. For example, if ABCDEF are added to the
/// stream, one reader may get ABDE and the other may get CF.
/// Each reader reads items from the stream as they become available.
/// Otherwise, if a maximum _capacity has been imposed, the writer
/// and reader could become mutually deadlocked.
///
/// When there are multiple blocked readers, any of the readers
/// may get the next object(s) added.
/// </remarks>
internal override Collection<object> ReadToEnd()
{
// NTRAID#Windows Out Of Band Releases-925566-2005/12/07-JonN
return Read(Int32.MaxValue);
}
/// <summary>
/// Reads objects currently in the stream, but does not block.
/// </summary>
/// <returns>An array of zero or more objects.</returns>
/// <remarks>
/// This method performs a read of objects currently in the
/// stream. The method will block until exclusive access to the
/// stream is acquired. If there are no objects in the stream,
/// an empty array is returned.
/// </remarks>
/// <param name="maxRequested">
/// Return no more than maxRequested objects.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="maxRequested"/> is less than 0
/// </exception>
internal override Collection<object> NonBlockingRead(int maxRequested)
{
Collection<object> results = null;
bool raiseEvents = false;
if (maxRequested == 0)
{
return new Collection<object>();
}
if (maxRequested < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested);
}
try
{
lock (_monitorObject)
{
int readCount = _objects.Count;
if (readCount > maxRequested)
{
// 2004/06/30-JonN Safe cast since 0 < maxRequested < readCount
readCount = (int)maxRequested;
}
if (readCount > 0)
{
results = new Collection<object>();
for (int i = 0; i < readCount; i++)
{
results.Add(_objects[i]);
}
raiseEvents = true;
_objects.RemoveRange(0, readCount);
}
}
}
finally
{
if (raiseEvents)
{
RaiseEvents();
}
}
return results ?? new Collection<object>();
}
/// <summary>
/// Peek the next object.
/// </summary>
/// <returns>
/// The next object in the stream or AutomationNull.Value if the stream is empty
/// </returns>
/// <exception cref="PipelineClosedException">The ObjectStream is closed.</exception>
internal override object Peek()
{
object result = null;
lock (_monitorObject)
{
if (EndOfPipeline || _objects.Count == 0)
{
result = AutomationNull.Value;
}
else
{
result = _objects[0];
}
}
return result;
}
#endregion Read Methods
#region Write Methods
/// <summary>
/// Write objects to the underlying stream.
/// </summary>
/// <param name="obj">Object or enumeration to read from.</param>
/// <param name="enumerateCollection">
/// If enumerateCollection is true, and <paramref name="obj"/>
/// is an enumeration according to LanguagePrimitives.GetEnumerable,
/// the objects in the enumeration will be unrolled and
/// written separately. Otherwise, <paramref name="obj"/>
/// will be written as a single object.
/// </param>
/// <returns>The number of objects written.</returns>
/// <exception cref="PipelineClosedException">
/// The underlying stream is closed
/// </exception>
/// <remarks>
/// If the enumeration contains elements equal to
/// AutomationNull.Value, they are ignored.
/// This can cause the return value to be less than the size of
/// the collection.
/// </remarks>
internal override int Write(object obj, bool enumerateCollection)
{
// it is permitted to write null objects
if (obj == AutomationNull.Value)
{
// NTRAID#Windows Out Of Band Releases-926213-2005/12/16-JonN
// We no longer break on AutomationNull.Value,
// we just ignore it
return 0;
}
if (!IsOpen)
{
// NTRAID#Windows Out Of Band Releases-925742-2005/12/07-JonN
string message = PipelineStrings.WriteToClosedPipeline;
Exception e = new PipelineClosedException(message);
throw e;
}
// We want to write the objects as one block, not individually
// We do not want to hold the stream locked during the enumeration
List<object> a = new List<object>();
IEnumerable enumerable = null;
if (enumerateCollection)
{
enumerable = LanguagePrimitives.GetEnumerable(obj);
}
if (enumerable == null)
a.Add(obj);
else
{
foreach (object o in enumerable)
{
// 879023-2003/10/28-JonN
// Outputting stops when receiving a AutomationNull.Value
// 2003/10/28-JonN There is a window where another
// thread could modify the array to contain
// AutomationNull.Value, but I'm not going to deal with it.
if (AutomationNull.Value == o)
{
// NTRAID#Windows Out Of Band Releases-926213-2005/12/16-JonN
// We no longer break on AutomationNull.Value,
// we just ignore it
continue;
}
a.Add(o);
}
}
int objectsWritten = 0;
int objectsToWrite = a.Count;
while (objectsToWrite > 0)
{
bool raiseEvents = false;
// wait for buffer available
// false indicates EndOfPipeline
if (!WaitWrite())
{
break;
}
try
{
lock (_monitorObject)
{
if (!IsOpen)
{
// NOTE: lock is released in finally
break;
}
// determine the maximum number of objects that
// can be written to the stream. Note: performing
// subtraction to ensure we don't have an
// overflow exception
int freeSpace = _capacity - _objects.Count;
if (freeSpace <= 0)
{
// NOTE: lock is released in finally
continue;
}
int writeCount = objectsToWrite;
if (writeCount > freeSpace)
{
// Note that we have already established that
// 0 < freeSpace < writeCount,
// so the cast is safe.
writeCount = freeSpace;
}
try
{
// determine if we can write to the stream in
// a single call.
if (writeCount == a.Count)
{
System.Management.Automation.Diagnostics.Assert
(objectsWritten == 0, "objectsWritten == 0");
_objects.AddRange(a);
objectsWritten += writeCount;
objectsToWrite -= writeCount;
System.Management.Automation.Diagnostics.Assert
(objectsToWrite == 0, "objectsToWrite == 0");
}
else
{
System.Management.Automation.Diagnostics.Assert
(writeCount > 0, "writeCount > 0");
List<object> a2 = a.GetRange(objectsWritten, writeCount);
_objects.AddRange(a2);
objectsWritten += writeCount;
objectsToWrite -= writeCount;
}
}
finally
{
raiseEvents = true;
}
}
}
finally
{
if (raiseEvents)
{
RaiseEvents();
}
}
}
return objectsWritten;
}
#endregion Write Methods
// 905990-2005/05/10-JonN Removed IDisposable
#region Design For Testability
/// <summary>
/// These methods are necessary to provide the ObjectStreamTest BVT
/// access to the internal handler DataReady. The EventInfo
/// reflection class does not give access to internal events.
/// </summary>
/// <param name="eventHandler"></param>
private void DFT_AddHandler_OnDataReady(EventHandler eventHandler)
{
DataReady += eventHandler;
}
private void DFT_RemoveHandler_OnDataReady(EventHandler eventHandler)
{
DataReady -= eventHandler;
}
#endregion Design For Testability
#region IDisposable
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
lock (_monitorObject)
{
if (_disposed)
{
return;
}
_disposed = true;
}
if (disposing)
{
_readHandle.Dispose();
_writeHandle.Dispose();
_writeClosedHandle.Dispose();
_readClosedHandle.Dispose();
_readWaitHandle?.Dispose();
_writeWaitHandle?.Dispose();
if (_reader != null)
{
_reader.Close();
_reader.WaitHandle.Dispose();
}
if (_writer != null)
{
_writer.Close();
_writer.WaitHandle.Dispose();
}
}
}
#endregion IDisposable
}
/// <summary>
/// An object stream using a PSDataCollection as the object store.
/// This stream lets user to supply a custom PSDataCollection instance
/// to use as the stream's object store.
///
/// This stream is designed to be used with the user supplied
/// PSDataBuffers. For internal only purposes use ObjectStream.
/// </summary>
internal sealed class PSDataCollectionStream<T> : ObjectStreamBase
{
#region Private Fields
private readonly PSDataCollection<T> _objects;
private readonly Guid _psInstanceId;
private bool _isOpen;
private PipelineWriter _writer;
private PipelineReader<object> _objectReader;
private PipelineReader<PSObject> _psobjectReader;
private PipelineReader<object> _objectReaderForPipeline;
private PipelineReader<PSObject> _psobjectReaderForPipeline;
private readonly object _syncObject = new object();
private bool _disposed = false;
#endregion
#region Constructors
/// <summary>
/// Creates the stream and uses the supplied <paramref name="storeToUse"/>
/// as the object store.
/// </summary>
/// <param name="psInstanceId">
/// Guid of Powershell instance creating this stream.
/// </param>
/// <param name="storeToUse">
/// A PSDataCollection instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// 1. storeToUse is null
/// </exception>
internal PSDataCollectionStream(Guid psInstanceId, PSDataCollection<T> storeToUse)
{
if (storeToUse == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(storeToUse));
}
_objects = storeToUse;
_psInstanceId = psInstanceId;
_isOpen = true;
// increment ref count for the store. PowerShell engine
// is about to use this store.
storeToUse.AddRef();
storeToUse.DataAdded += HandleDataAdded;
storeToUse.Completed += HandleClosed;
}
#endregion
#region Properties
/// <summary>
/// Gets the PSDataCollection used to store data for this stream.
/// </summary>
internal PSDataCollection<T> ObjectStore
{
get
{
return _objects;
}
}
#endregion
#region Virtual Implementation
/// <summary>
/// Returns the number of objects in the stream.
/// </summary>
internal override int Count
{
get
{
return _objects.Count;
}
}
/// <summary>
/// This is not supported.
/// </summary>
internal override bool EndOfPipeline
{
get
{
bool endOfStream = true;
lock (_syncObject)
{
endOfStream = (_objects.Count == 0 && !_isOpen);
}
return endOfStream;
}
}
/// <summary>
/// Check if the stream is open for further writes.
/// </summary>
/// <returns>True if the stream is open, false if not.</returns>
/// <remarks>
/// IsOpen returns true until the first call to Close(). Writers should
/// check IsOpen to determine if a write operation can be made.
/// </remarks>
internal override bool IsOpen
{
get
{
// check both the current stream and the object store.
return _isOpen && _objects.IsOpen;
}
}
/// <summary>
/// This is not supported.
/// </summary>
internal override int MaxCapacity
{
get
{
#pragma warning disable 56503
throw PSTraceSource.NewNotSupportedException();
#pragma warning restore 56503
}
}
/// <summary>
/// Return a PipelineReader(object) for this stream.
/// </summary>
internal override PipelineReader<object> ObjectReader
{
get
{
if (_objectReader == null)
{
lock (_syncObject)
{
_objectReader ??= new PSDataCollectionReader<T, object>(this);
}
}
return _objectReader;
}
}
/// <summary>
/// Creates an Object Reader for the pipeline.
/// </summary>
/// <param name="computerName">Computer name that the pipeline specifies.</param>
/// <param name="runspaceId">Runspace id that the pipeline specifies.</param>
/// <remarks>the computer name and runspace id are associated with the
/// reader so as to enable cmdlets to identify which computer name runspace does
/// the object that this stream writes belongs to</remarks>
internal PipelineReader<object> GetObjectReaderForPipeline(string computerName, Guid runspaceId)
{
if (_objectReaderForPipeline == null)
{
lock (_syncObject)
{
_objectReaderForPipeline ??=
new PSDataCollectionPipelineReader<T, object>(this, computerName, runspaceId);
}
}
return _objectReaderForPipeline;
}
/// <summary>
/// Return a PipelineReader(PSObject) for this stream.
/// </summary>
internal override PipelineReader<PSObject> PSObjectReader
{
get
{
if (_psobjectReader == null)
{
lock (_syncObject)
{
_psobjectReader ??= new PSDataCollectionReader<T, PSObject>(this);
}
}
return _psobjectReader;
}
}
/// <summary>
/// Creates a PSObject Reader for this pipeline.
/// </summary>
/// <param name="computerName">Computer name that the pipeline specifies.</param>
/// <param name="runspaceId">Runspace id that the pipeline specifies.</param>
/// <remarks>the computer name and runspace id are associated with the
/// reader so as to enable cmdlets to identify which computer name runspace does
/// the object that this stream writes belongs to</remarks>
internal PipelineReader<PSObject> GetPSObjectReaderForPipeline(string computerName, Guid runspaceId)
{
if (_psobjectReaderForPipeline == null)
{
lock (_syncObject)
{
_psobjectReaderForPipeline ??=
new PSDataCollectionPipelineReader<T, PSObject>(this, computerName, runspaceId);
}
}
return _psobjectReaderForPipeline;
}
/// <summary>
/// The object writer for this stream.
/// </summary>
/// <remarks>
/// This field is allocated on first demand and
/// returned on subsequent calls.
/// </remarks>
internal override PipelineWriter ObjectWriter
{
get
{
if (_writer == null)
{
lock (_syncObject)
{
_writer ??= new PSDataCollectionWriter<T>(this) as PipelineWriter;
}
}
return _writer;
}
}
/// <summary>
/// Read handle associated with this stream.
/// </summary>
internal override WaitHandle ReadHandle
{
get
{
return _objects.WaitHandle;
}
}
#endregion
#region Write Abstractions
/// <summary>
/// Write object(s) to the databuffer.
/// </summary>
/// <param name="obj"></param>
/// <param name="enumerateCollection"></param>
/// <returns></returns>
internal override int Write(object obj, bool enumerateCollection)
{
// it is permitted to write null objects
if (obj == AutomationNull.Value)
{
// We no longer break on AutomationNull.Value,
// we just ignore it
return 0;
}
if (!IsOpen)
{
// NTRAID#Windows Out Of Band Releases-925742-2005/12/07-JonN
string message = PSDataBufferStrings.WriteToClosedBuffer;
Exception e = new PipelineClosedException(message);
throw e;
}
// We want to write the objects as one block, not individually
// We do not want to hold the stream locked during the enumeration
Collection<T> objectsToAdd = new Collection<T>();
IEnumerable enumerable = null;
if (enumerateCollection)
{
enumerable = LanguagePrimitives.GetEnumerable(obj);
}
if (enumerable == null)
{
objectsToAdd.Add((T)LanguagePrimitives.ConvertTo(obj,
typeof(T), Globalization.CultureInfo.InvariantCulture));
}
else
{
foreach (object o in enumerable)
{
// Outputting stops when receiving a AutomationNull.Value
// There is a window where another thread could modify the
// array to contain AutomationNull.Value,
// but I'm not going to deal with it.
if (AutomationNull.Value == o)
{
// We no longer break on AutomationNull.Value,
// we just ignore it
continue;
}
objectsToAdd.Add((T)LanguagePrimitives.ConvertTo(obj,
typeof(T), Globalization.CultureInfo.InvariantCulture));
}
}
_objects.InternalAddRange(_psInstanceId, objectsToAdd);
return objectsToAdd.Count;
}
#endregion
#region Virtual Method Implementation
/// <summary>
/// This stream do not perform close operations on the buffer.
/// It is upto the user to close the buffers as and when needed.
/// However this method notifies the buffer by decrementing the
/// ref count.
/// </summary>
internal override void Close()
{
bool raiseEvents = false;
lock (_syncObject)
{
// Make sure decrementref is called only once. if this
// stream is already closed..no need to decrement again.
// isOpen controls if this current stream is open or not.
if (_isOpen)
{
// Decrement ref count (and other event handlers) for the store.
// PowerShell engine is done using this store.
_objects.DecrementRef();
_objects.DataAdded -= HandleDataAdded;
_objects.Completed -= HandleClosed;
raiseEvents = true;
_isOpen = false;
}
}
if (raiseEvents)
{
FireDataReadyEvent(this, EventArgs.Empty);
}
}
#endregion
#region Event Handlers
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleClosed(object sender, EventArgs e)
{
Close();
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleDataAdded(object sender, DataAddedEventArgs e)
{
FireDataReadyEvent(this, EventArgs.Empty);
}
#endregion Event Handlers
#region IDisposable
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all resources.</param>
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
lock (_syncObject)
{
if (_disposed)
{
return;
}
_disposed = true;
}
if (disposing)
{
_objects.Dispose();
Close();
if (_objectReaderForPipeline != null)
{
((PSDataCollectionPipelineReader<T, object>)_objectReaderForPipeline).Dispose();
}
if (_psobjectReaderForPipeline != null)
{
((PSDataCollectionPipelineReader<T, PSObject>)_psobjectReaderForPipeline).Dispose();
}
}
}
#endregion IDisposable
}
}
|