diff options
author | Jan Tattermusch <jtattermusch@google.com> | 2015-07-23 17:26:35 -0700 |
---|---|---|
committer | Jan Tattermusch <jtattermusch@google.com> | 2015-07-23 18:27:16 -0700 |
commit | f7cfc8a7b8652bbf81e336f3e62a7cd0da8be2f0 (patch) | |
tree | 46a84829200c7eca4cba8e62db8654ceee2707ef | |
parent | 0846b68eb7bc6f6f63770880a2d48e787274ef67 (diff) |
implemented cancellation support for MathService.Fib
-rw-r--r-- | src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs | 33 | ||||
-rw-r--r-- | src/csharp/Grpc.Examples/MathServiceImpl.cs | 9 |
2 files changed, 40 insertions, 2 deletions
diff --git a/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs b/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs index 7a957c5b6f..6edc07912b 100644 --- a/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs +++ b/src/csharp/Grpc.Examples.Tests/MathClientServerTests.cs @@ -132,6 +132,39 @@ namespace math.Tests }).Wait(); } + [Test] + public void FibWithCancel() + { + Task.Run(async () => + { + var cts = new CancellationTokenSource(); + + using (var call = client.Fib(new FibArgs.Builder { Limit = 0 }.Build(), + cancellationToken: cts.Token)) + { + List<long> responses = new List<long>(); + + try + { + while (await call.ResponseStream.MoveNext()) + { + if (responses.Count == 0) + { + cts.CancelAfter(500); // make sure we cancel soon + } + responses.Add(call.ResponseStream.Current.Num_); + } + Assert.Fail(); + } + catch (RpcException e) + { + Assert.IsTrue(responses.Count > 0); + Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode); + } + } + }).Wait(); + } + // TODO: test Fib with limit=0 and cancellation [Test] public void Sum() diff --git a/src/csharp/Grpc.Examples/MathServiceImpl.cs b/src/csharp/Grpc.Examples/MathServiceImpl.cs index 3dd0f53a0d..dd26b1d350 100644 --- a/src/csharp/Grpc.Examples/MathServiceImpl.cs +++ b/src/csharp/Grpc.Examples/MathServiceImpl.cs @@ -54,8 +54,13 @@ namespace math { if (request.Limit <= 0) { - // TODO(jtattermusch): support cancellation - throw new NotImplementedException("Not implemented yet"); + // keep streaming the sequence until cancelled. + IEnumerator<Num> fibEnumerator = FibInternal(long.MaxValue).GetEnumerator(); + while (!context.CancellationToken.IsCancellationRequested && fibEnumerator.MoveNext()) + { + await responseStream.WriteAsync(fibEnumerator.Current); + await Task.Delay(100); + } } if (request.Limit > 0) |