You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestAsyncStreamReader.cs 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #pragma warning disable IDE0073
  2. // Copyright 2019 The 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. using System.Threading.Channels;
  16. using Grpc.Core;
  17. namespace Microsoft.AutoGen.RuntimeGateway.Grpc.Tests.Helpers.Grpc;
  18. public class TestAsyncStreamReader<T> : IDisposable, IAsyncStreamReader<T>
  19. where T : class
  20. {
  21. private readonly Channel<T> _channel;
  22. private readonly ServerCallContext _serverCallContext;
  23. public T Current { get; private set; } = null!;
  24. public TestAsyncStreamReader(ServerCallContext serverCallContext)
  25. {
  26. _channel = Channel.CreateUnbounded<T>();
  27. _serverCallContext = serverCallContext;
  28. }
  29. public void AddMessage(T message)
  30. {
  31. if (!_channel.Writer.TryWrite(message))
  32. {
  33. throw new InvalidOperationException("Unable to write message.");
  34. }
  35. }
  36. public void Complete()
  37. {
  38. _channel.Writer.Complete();
  39. }
  40. public async Task<bool> MoveNext(CancellationToken cancellationToken)
  41. {
  42. _serverCallContext.CancellationToken.ThrowIfCancellationRequested();
  43. if (await _channel.Reader.WaitToReadAsync(cancellationToken) &&
  44. _channel.Reader.TryRead(out var message))
  45. {
  46. Current = message;
  47. return true;
  48. }
  49. else
  50. {
  51. Current = null!;
  52. return false;
  53. }
  54. }
  55. public void Dispose()
  56. {
  57. Complete();
  58. }
  59. }