ClientResponseStream.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace Grpc.Core.Internal
  21. {
  22. internal class ClientResponseStream<TRequest, TResponse> : IAsyncStreamReader<TResponse>
  23. where TRequest : class
  24. where TResponse : class
  25. {
  26. readonly AsyncCall<TRequest, TResponse> call;
  27. TResponse current;
  28. public ClientResponseStream(AsyncCall<TRequest, TResponse> call)
  29. {
  30. this.call = call;
  31. }
  32. public TResponse Current
  33. {
  34. get
  35. {
  36. if (current == null)
  37. {
  38. throw new InvalidOperationException("No current element is available.");
  39. }
  40. return current;
  41. }
  42. }
  43. public async Task<bool> MoveNext(CancellationToken token)
  44. {
  45. var cancellationTokenRegistration = token.CanBeCanceled ? token.Register(() => call.Cancel()) : (IDisposable) null;
  46. using (cancellationTokenRegistration)
  47. {
  48. var result = await call.ReadMessageAsync().ConfigureAwait(false);
  49. this.current = result;
  50. if (result == null)
  51. {
  52. await call.StreamingResponseCallFinishedTask.ConfigureAwait(false);
  53. return false;
  54. }
  55. return true;
  56. }
  57. }
  58. public void Dispose()
  59. {
  60. // TODO(jtattermusch): implement the semantics of stream disposal.
  61. }
  62. }
  63. }