-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathHttpClientWorkerJob.cs
More file actions
77 lines (66 loc) · 2.51 KB
/
Copy pathHttpClientWorkerJob.cs
File metadata and controls
77 lines (66 loc) · 2.51 KB
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
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Netling.Core.Models;
namespace Netling.Core.HttpClientWorker
{
public class HttpClientWorkerJob : IWorkerJob
{
private readonly int _index;
private Uri _uri;
private readonly Stopwatch _stopwatch;
private readonly Stopwatch _localStopwatch;
private readonly WorkerThreadResult _workerThreadResult;
private readonly HttpClient _httpClient;
// Used to approximately calculate bandwidth
private static readonly int MissingHeaderLength = "HTTP/1.1 200 OK\r\nContent-Length: 123\r\nContent-Type: text/plain\r\n\r\n".Length;
public HttpClientWorkerJob()
{
}
public HttpClientWorkerJob(Uri uri)
{
_uri = uri;
}
public void Initialize(Uri uri)
{
_uri = uri;
}
private HttpClientWorkerJob(int index, Uri uri, WorkerThreadResult workerThreadResult)
{
_index = index;
_uri = uri;
_stopwatch = Stopwatch.StartNew();
_localStopwatch = new Stopwatch();
_workerThreadResult = workerThreadResult;
_httpClient = new HttpClient();
}
public async ValueTask DoWork()
{
_localStopwatch.Restart();
using (var response = await _httpClient.GetAsync(_uri))
{
var contentStream = await response.Content.ReadAsStreamAsync();
var length = contentStream.Length + response.Headers.ToString().Length + MissingHeaderLength;
var responseTime = (float)_localStopwatch.ElapsedTicks / Stopwatch.Frequency * 1000;
var statusCode = (int)response.StatusCode;
if (statusCode < 400)
{
_workerThreadResult.Add((int)_stopwatch.ElapsedMilliseconds / 1000, length, responseTime, statusCode, _index < 10);
}
else
{
_workerThreadResult.AddError((int)_stopwatch.ElapsedMilliseconds / 1000, responseTime, statusCode, _index < 10);
}
}
}
public WorkerThreadResult GetResults()
{
return _workerThreadResult;
}
public ValueTask<IWorkerJob> Init(int index, WorkerThreadResult workerThreadResult)
{
return new ValueTask<IWorkerJob>(new HttpClientWorkerJob(index, _uri, workerThreadResult));
}
}
}