code_junkie

Is there a blocking StreamReader, TextReader, or StringReader in .NET?

Nov 12th, 2011
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. public class BlockingStream: Stream
  2. {
  3. private readonly Stream _stream;
  4.  
  5. public BlockingStream(Stream stream)
  6. {
  7. if(!stream.CanSeek)
  8. throw new ArgumentException("Stream must support seek", "stream");
  9. _stream = stream;
  10. }
  11.  
  12. public override void Flush()
  13. {
  14. lock (_stream)
  15. {
  16. _stream.Flush();
  17. Monitor.Pulse(_stream);
  18. }
  19. }
  20.  
  21. public override long Seek(long offset, SeekOrigin origin)
  22. {
  23. lock (_stream)
  24. {
  25. long res = _stream.Seek(offset, origin);
  26. Monitor.Pulse(_stream);
  27. return res;
  28. }
  29. }
  30.  
  31. public override void SetLength(long value)
  32. {
  33. lock (_stream)
  34. {
  35. _stream.SetLength(value);
  36. Monitor.Pulse(_stream);
  37. }
  38. }
  39.  
  40. public override int Read(byte[] buffer, int offset, int count)
  41. {
  42. lock (_stream)
  43. {
  44. do
  45. {
  46. int read = _stream.Read(buffer, offset, count);
  47. if (read > 0)
  48. return read;
  49. Monitor.Wait(_stream);
  50. } while (true);
  51. }
  52. }
  53.  
  54. public override void Write(byte[] buffer, int offset, int count)
  55. {
  56. lock (_stream)
  57. {
  58. long currentPosition = _stream.Position;
  59. _stream.Position = _stream.Length;
  60. _stream.Write(buffer, offset, count);
  61. _stream.Position = currentPosition;
  62. Monitor.Pulse(_stream);
  63. }
  64. }
  65.  
  66. public override bool CanRead
  67. {
  68. get
  69. {
  70. lock (_stream)
  71. {
  72. return _stream.CanRead;
  73. }
  74. }
  75. }
  76.  
  77. public override bool CanSeek
  78. {
  79. get
  80. {
  81. lock (_stream)
  82. {
  83. return _stream.CanSeek;
  84. }
  85. }
  86. }
  87.  
  88. public override bool CanWrite
  89. {
  90. get
  91. {
  92. lock (_stream)
  93. {
  94. return _stream.CanWrite;
  95. }
  96. }
  97. }
  98.  
  99. public override long Length
  100. {
  101. get
  102. {
  103. lock (_stream)
  104. {
  105. return _stream.Length;
  106. }
  107. }
  108. }
  109.  
  110. public override long Position
  111. {
  112. get
  113. {
  114. lock (_stream)
  115. {
  116. return _stream.Position;
  117. }
  118. }
  119. set
  120. {
  121. lock (_stream)
  122. {
  123. _stream.Position = value;
  124. Monitor.Pulse(_stream);
  125. }
  126. }
  127. }
  128. }
Add Comment
Please, Sign In to add comment