File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ < Query Kind = "Program" >
2
+ < Namespace > System . Net . Http < / Namespace >
3
+ < Namespace > System . Threading . Tasks < / Namespace >
4
+ < / Query >
5
+
6
+ HttpClient _client = new HttpClient
7
+ {
8
+ Timeout = TimeSpan . FromSeconds ( 5 )
9
+ } ;
10
+ SemaphoreSlim _gate = new SemaphoreSlim ( 20 ) ;
11
+
12
+ void Main ( )
13
+ {
14
+ Task . WaitAll ( CreateCalls ( ) . ToArray ( ) ) ;
15
+ }
16
+
17
+ public IEnumerable < Task > CreateCalls ( )
18
+ {
19
+ for ( int i = 0 ; i < 500 ; i ++ )
20
+ {
21
+ yield return CallGoogle ( ) ;
22
+ }
23
+ }
24
+
25
+
26
+ public async Task CallGoogle ( )
27
+ {
28
+ try
29
+ {
30
+ await _gate . WaitAsync ( ) ;
31
+ var response = await _client . GetAsync ( "https://google.com" ) ;
32
+ _gate . Release ( ) ;
33
+
34
+ response . StatusCode . Dump ( ) ;
35
+ }
36
+ catch ( Exception e )
37
+ {
38
+ e . Message . Dump ( ) ;
39
+ }
40
+ }
Original file line number Diff line number Diff line change
1
+ < Query Kind = "Program" >
2
+ < Namespace > System . Threading . Tasks < / Namespace >
3
+ < / Query >
4
+
5
+ SemaphoreSlim gate = new SemaphoreSlim ( 1 ) ;
6
+
7
+ async Task Main ( )
8
+ {
9
+ for ( int i = 0 ; i < 10 ; i ++ )
10
+ {
11
+ "Start" . Dump ( ) ;
12
+ await gate . WaitAsync ( ) ;
13
+ "Do Some Work" . Dump ( ) ;
14
+ gate . Release ( ) ;
15
+ "Finish" . Dump ( ) ;
16
+ }
17
+ }
You can’t perform that action at this time.
0 commit comments