@@ -29,11 +29,11 @@ namespace Client
2929{
3030 public class Program
3131 {
32- static Random RNG = new Random ( ) ;
32+ private static readonly Random Random = new Random ( ) ;
3333
3434 static async Task Main ( string [ ] args )
3535 {
36- var channel = GrpcChannel . ForAddress ( "https://localhost:5001" ) ;
36+ using var channel = GrpcChannel . ForAddress ( "https://localhost:5001" ) ;
3737 var client = new Aggregator . AggregatorClient ( channel ) ;
3838
3939 await ServerStreamingCallExample ( client ) ;
@@ -49,39 +49,35 @@ private static async Task ServerStreamingCallExample(Aggregator.AggregatorClient
4949 var cts = new CancellationTokenSource ( ) ;
5050 cts . CancelAfter ( TimeSpan . FromSeconds ( 3.5 ) ) ;
5151
52- using ( var replies = client . SayHellos ( new HelloRequest { Name = "AggregatorClient" } , cancellationToken : cts . Token ) )
52+ using var call = client . SayHellos ( new HelloRequest { Name = "AggregatorClient" } , cancellationToken : cts . Token ) ;
53+ try
5354 {
54- try
55+ await foreach ( var message in call . ResponseStream . ReadAllAsync ( ) )
5556 {
56- await foreach ( var message in replies . ResponseStream . ReadAllAsync ( ) )
57- {
58- Console . WriteLine ( "Greeting: " + message . Message ) ;
59- }
60- }
61- catch ( RpcException ex ) when ( ex . StatusCode == StatusCode . Cancelled )
62- {
63- Console . WriteLine ( "Stream cancelled." ) ;
57+ Console . WriteLine ( "Greeting: " + message . Message ) ;
6458 }
6559 }
60+ catch ( RpcException ex ) when ( ex . StatusCode == StatusCode . Cancelled )
61+ {
62+ Console . WriteLine ( "Stream cancelled." ) ;
63+ }
6664 }
6765
6866 private static async Task ClientStreamingCallExample ( Aggregator . AggregatorClient client )
6967 {
70- using ( var call = client . AccumulateCount ( ) )
68+ using var call = client . AccumulateCount ( ) ;
69+ for ( var i = 0 ; i < 3 ; i ++ )
7170 {
72- for ( var i = 0 ; i < 3 ; i ++ )
73- {
74- var count = RNG . Next ( 5 ) ;
75- Console . WriteLine ( $ "Accumulating with { count } ") ;
76- await call . RequestStream . WriteAsync ( new CounterRequest { Count = count } ) ;
77- await Task . Delay ( 2000 ) ;
78- }
71+ var count = Random . Next ( 5 ) ;
72+ Console . WriteLine ( $ "Accumulating with { count } ") ;
73+ await call . RequestStream . WriteAsync ( new CounterRequest { Count = count } ) ;
74+ await Task . Delay ( 2000 ) ;
75+ }
7976
80- await call . RequestStream . CompleteAsync ( ) ;
77+ await call . RequestStream . CompleteAsync ( ) ;
8178
82- var response = await call ;
83- Console . WriteLine ( $ "Count: { response . Count } ") ;
84- }
79+ var response = await call ;
80+ Console . WriteLine ( $ "Count: { response . Count } ") ;
8581 }
8682 }
8783}
0 commit comments