Skip to content

Commit 80f8d43

Browse files
committed
Dispose internally created HttpClients.
1 parent 7ebcdb7 commit 80f8d43

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

WebPush/WebPushClient.cs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
namespace WebPush
1313
{
14-
public class WebPushClient
14+
public class WebPushClient : IDisposable
1515
{
1616
// default TTL is 4 weeks.
1717
private const int DefaultTtl = 2419200;
@@ -21,6 +21,9 @@ public class WebPushClient
2121
private HttpClient _httpClient;
2222
private VapidDetails _vapidDetails;
2323

24+
// Used so we only cleanup internally created http clients
25+
private bool _isHttpClientInternallyCreated;
26+
2427
public WebPushClient()
2528
{
2629

@@ -36,10 +39,23 @@ public WebPushClient(HttpClientHandler httpClientHandler)
3639
_httpClientHandler = httpClientHandler;
3740
}
3841

39-
protected HttpClient HttpClient =>
40-
_httpClient ?? (_httpClient = _httpClientHandler == null
41-
? new HttpClient()
42-
: new HttpClient(_httpClientHandler));
42+
protected HttpClient HttpClient
43+
{
44+
get
45+
{
46+
if (_httpClient != null)
47+
{
48+
return _httpClient;
49+
}
50+
51+
_isHttpClientInternallyCreated = true;
52+
_httpClient = (_httpClient = _httpClientHandler == null
53+
? new HttpClient()
54+
: new HttpClient(_httpClientHandler));
55+
56+
return _httpClient;
57+
}
58+
}
4359

4460
/// <summary>
4561
/// When sending messages to a GCM endpoint you need to set the GCM API key
@@ -361,5 +377,14 @@ private static void HandleResponse(HttpResponseMessage response, PushSubscriptio
361377

362378
throw new WebPushException(message, response.StatusCode, response.Headers, subscription);
363379
}
380+
381+
public void Dispose()
382+
{
383+
if (_httpClient != null && _isHttpClientInternallyCreated)
384+
{
385+
_httpClient.Dispose();
386+
_httpClient = null;
387+
}
388+
}
364389
}
365390
}

0 commit comments

Comments
 (0)