Last active
November 4, 2020 15:46
-
-
Save trnktms/f6eac68d7c9027a3e535b7cd23865d70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Discovering.Sitecore10.Processors.PublishEnd.Services | |
{ | |
public class RenderingHostBatchingCacheClearer | |
{ | |
private readonly HttpClient _httpClient; | |
private readonly object _lock = new object(); | |
private readonly Timer _timer; | |
private readonly HashSet<string> _endpoints = new HashSet<string>(); | |
public RenderingHostBatchingCacheClearer(TimeSpan batchingTimeout, HttpClient httpClient) | |
{ | |
_httpClient = httpClient; | |
_timer = new Timer(batchingTimeout.TotalMilliseconds) | |
{ | |
AutoReset = false, | |
Enabled = false | |
}; | |
_timer.Elapsed += (s, a) => { TriggerCacheClear(); }; | |
} | |
public void AddEndpoints(IEnumerable<string> endpoints) | |
{ | |
if (endpoints == null || !endpoints.Any()) | |
return; | |
lock (_lock) | |
foreach (var endpoint in endpoints) | |
_endpoints.Add(endpoint); | |
_timer.Stop(); | |
_timer.Start(); | |
} | |
public int GetEndPointsCount() | |
{ | |
lock (_lock) | |
return _endpoints.Count; | |
} | |
private async void TriggerCacheClear() | |
{ | |
string[] endpoints; | |
lock (_lock) | |
{ | |
if (_endpoints.Count == 0) | |
return; | |
endpoints = _endpoints.ToArray(); | |
} | |
foreach (var endpoint in endpoints) | |
{ | |
try | |
{ | |
var response = await _httpClient.GetAsync(endpoint); | |
if (!response.IsSuccessStatusCode) | |
continue; | |
} | |
catch (Exception e) | |
{ | |
Log.Error(e.Message, e, this); | |
} | |
finally | |
{ | |
// remove items from the list if calling the endpoint returned with successful status or exception happened | |
lock (_lock) | |
_endpoints.Remove(endpoint); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment