/
WebClientPool.cs
78 lines (71 loc) · 2.32 KB
/
WebClientPool.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace WebClientPool.Models.Pools
{
/// <summary>
/// Provides a pooled WebClient.
/// </summary>
/// <typeparam name="T">WebClient.</typeparam>
public class WebClientPool<T> : IDisposable where T : IDisposable, new()
{
private readonly ImmutableList<WebClientInfo<T>> _clients;
/// <summary>
/// Initialize.
/// </summary>
/// <param name="size">Max number of pooled WebClient.</param>
/// <param name="postProcessing">Action to be performed after the WebClient instance has been created.</param>
public WebClientPool(int size, Action<T> postProcessing)
{
var clients = new List<WebClientInfo<T>>();
foreach (var i in Enumerable.Range(0, size))
{
var client = new T();
postProcessing?.Invoke(client);
clients.Add(new WebClientInfo<T>(i, client));
}
_clients = ImmutableList.Create(clients.ToArray());
}
/// <summary>
/// Get the WebClient that is available.
/// </summary>
/// <returns>The WebClient that is available.</returns>
public async Task<IWebClientInfo<T>> GetWebClient()
{
return await Task.Factory.StartNew(() =>
{
while (true)
{
foreach (var client in _clients.Where(client => !client.IsBusy))
{
client.IsBusy = true;
return client;
}
Thread.Sleep(100);
}
});
}
/// <summary>
/// Return the WebClient used.
/// </summary>
/// <param name="webClient">The used WebClient.</param>
public void ReturnWebClient(IWebClientInfo<T> webClient)
{
var client = _clients[webClient.Id];
client.IsBusy = false;
}
public void Dispose()
{
foreach (var client in _clients)
{
client.Dispose();
}
}
}
}