Skip to content

Commit

Permalink
Added WatchCancellationTokenSource (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
muratyuceer authored Nov 8, 2023
1 parent 23bb0c3 commit bf77bb3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ public ConsulConfigurationProvider(
_source = source;
_consulClientFactory = consulClientFactory;
_cancellationTokenSource = new CancellationTokenSource();
if (_source.WatchCancellationTokenSource != null)
{
_source.WatchCancellationTokenSource.Token.Register(() =>
{
if (!_disposed && !_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
}
});
}
}

public void Dispose()
Expand Down Expand Up @@ -143,7 +153,7 @@ private async Task PollingLoop(CancellationToken cancellationToken)
SetLastIndex(result);
consecutiveFailureCount = 0;
}
catch (Exception exception)
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
var wait =
_source.OnWatchException?.Invoke(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using Consul;
using Microsoft.Extensions.Configuration;
using Winton.Extensions.Configuration.Consul.Extensions;
Expand Down Expand Up @@ -47,6 +48,8 @@ public string KeyToRemove

public Func<ConsulWatchExceptionContext, TimeSpan>? OnWatchException { get; set; }

public CancellationTokenSource? WatchCancellationTokenSource { get; set; }

public bool Optional { get; set; } = false;

public IConfigurationParser Parser { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ public interface IConsulConfigurationSource : IConfigurationSource
/// </remarks>
Func<ConsulWatchExceptionContext, TimeSpan>? OnWatchException { get; set; }

/// <summary>
/// Gets or sets a <see cref="CancellationTokenSource" /> which can be used to cancel the background task that watches Consul for changes to this config.
/// </summary>
/// <remarks>
/// Cancelling the watch task by calling <c>Cancel()</c> on this <c>CancellationTokenSource</c> will completely terminate the watching process and it is not possible to restart it after this.
/// By default this configuration provider will terminate the watch task itself when the <c>ConsulConfigurationProvider</c> is disposed.
/// This functionality is only useful if you need to terminate the watch task early in response to some other event or want explicit control over when it is cancelled for some other reasons.
/// </remarks>
CancellationTokenSource? WatchCancellationTokenSource { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the config is optional.
/// </summary>
Expand Down

0 comments on commit bf77bb3

Please sign in to comment.