2
0

TimeoutStream.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.IO;
  7. using System.Runtime;
  8. // Enforces an overall timeout based on the TimeoutHelper passed in
  9. class TimeoutStream : DelegatingStream
  10. {
  11. TimeoutHelper timeoutHelper;
  12. public TimeoutStream(Stream stream, ref TimeoutHelper timeoutHelper)
  13. : base(stream)
  14. {
  15. if (!stream.CanTimeout)
  16. {
  17. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("stream", SR.GetString(SR.StreamDoesNotSupportTimeout));
  18. }
  19. this.timeoutHelper = timeoutHelper;
  20. }
  21. void UpdateReadTimeout()
  22. {
  23. this.ReadTimeout = TimeoutHelper.ToMilliseconds(this.timeoutHelper.RemainingTime());
  24. }
  25. void UpdateWriteTimeout()
  26. {
  27. this.WriteTimeout = TimeoutHelper.ToMilliseconds(this.timeoutHelper.RemainingTime());
  28. }
  29. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  30. {
  31. UpdateReadTimeout();
  32. return base.BeginRead(buffer, offset, count, callback, state);
  33. }
  34. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  35. {
  36. UpdateWriteTimeout();
  37. return base.BeginWrite(buffer, offset, count, callback, state);
  38. }
  39. public override int Read(byte[] buffer, int offset, int count)
  40. {
  41. UpdateReadTimeout();
  42. return base.Read(buffer, offset, count);
  43. }
  44. public override int ReadByte()
  45. {
  46. UpdateReadTimeout();
  47. return base.ReadByte();
  48. }
  49. public override void Write(byte[] buffer, int offset, int count)
  50. {
  51. UpdateWriteTimeout();
  52. base.Write(buffer, offset, count);
  53. }
  54. public override void WriteByte(byte value)
  55. {
  56. UpdateWriteTimeout();
  57. base.WriteByte(value);
  58. }
  59. }
  60. }