Skip to content

Commit e475368

Browse files
author
Anton Wieslander
committed
Semaphore
1 parent b6e868b commit e475368

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Semaphore/save_the_client.linq

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

Semaphore/the_gate.linq

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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+
}

0 commit comments

Comments
 (0)