11
11
12
12
namespace WebPush
13
13
{
14
- public class WebPushClient
14
+ public class WebPushClient : IDisposable
15
15
{
16
16
// default TTL is 4 weeks.
17
17
private const int DefaultTtl = 2419200 ;
@@ -21,6 +21,9 @@ public class WebPushClient
21
21
private HttpClient _httpClient ;
22
22
private VapidDetails _vapidDetails ;
23
23
24
+ // Used so we only cleanup internally created http clients
25
+ private bool _isHttpClientInternallyCreated ;
26
+
24
27
public WebPushClient ( )
25
28
{
26
29
@@ -36,10 +39,23 @@ public WebPushClient(HttpClientHandler httpClientHandler)
36
39
_httpClientHandler = httpClientHandler ;
37
40
}
38
41
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
+ }
43
59
44
60
/// <summary>
45
61
/// 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
361
377
362
378
throw new WebPushException ( message , response . StatusCode , response . Headers , subscription ) ;
363
379
}
380
+
381
+ public void Dispose ( )
382
+ {
383
+ if ( _httpClient != null && _isHttpClientInternallyCreated )
384
+ {
385
+ _httpClient . Dispose ( ) ;
386
+ _httpClient = null ;
387
+ }
388
+ }
364
389
}
365
390
}
0 commit comments