-
Notifications
You must be signed in to change notification settings - Fork 2
/
HighLevel_SemaphoreSlim.cs
36 lines (32 loc) · 1.2 KB
/
HighLevel_SemaphoreSlim.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading; //SemaphoreSlim
namespace ThrottledParallelism.Strategies
{
public class HighLevel_SemaphoreSlim : IGovernedParallelDownloader
{
private static readonly HttpClient client = new HttpClient();
public Task DownloadThemAllAsync(IEnumerable<Uri> uris, ProcessResult processResult, byte maxThreads)
{
var throttler = new SemaphoreSlim(maxThreads);
//Single Producer
//Waiting for all workers to finish
return Task.WhenAll(
uris.Select(async uri => //Multiple Workers
{
await throttler.WaitAsync(); //MaxDegreeOfParallelism
try { await WorkerAsync(uri, processResult); }
finally { throttler.Release(); }
}
));
}
async Task WorkerAsync(Uri uri, ProcessResult processResult)
{
var content = await client.GetStringAsync(uri).ConfigureAwait(false);
processResult(Thread.CurrentThread.ManagedThreadId.ToString(), content);
}
}
}