MutexLeaderElection 2.0.1

dotnet add package MutexLeaderElection --version 2.0.1
                    
NuGet\Install-Package MutexLeaderElection -Version 2.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MutexLeaderElection" Version="2.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MutexLeaderElection" Version="2.0.1" />
                    
Directory.Packages.props
<PackageReference Include="MutexLeaderElection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MutexLeaderElection --version 2.0.1
                    
#r "nuget: MutexLeaderElection, 2.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MutexLeaderElection@2.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MutexLeaderElection&version=2.0.1
                    
Install as a Cake Addin
#tool nuget:?package=MutexLeaderElection&version=2.0.1
                    
Install as a Cake Tool

Ibis.MutexLeaderElection

Implementation of the Leader Election pattern based on a distributed lock by taking a lease on an Azure Storage Blob:

Coordinate the actions performed by a collection of collaborating instances in a distributed application by electing one instance as the leader that assumes responsibility for managing the others. This can help to ensure that instances don't conflict with each other, cause contention for shared resources, or inadvertently interfere with the work that other instances are performing.

This repository is heavily based on the code provided in the link shown above, but with updated libs and available as a NuGet package.

Download the NuGet package NuGet Status

Usage

A sample application is included that demonstrates the use based on the following scenario:

  • A .Net Web Application hosts a background job
  • Multiple instances of the application are running (for example, in an Azure Kubernetes Service)
  • Only one instance should have a running background job

Normally one would consider moving the background job out of the Web Application into an Azure Function or an other alternative. That would be the recommended approach but there might me plenty of reasons why that is not doable. Therefore this solution is a practical approach.

Configuration

In the Startup.cs file the services should be configured:

public void ConfigureServices(IServiceCollection services)
{
    var distributedLockOptions = _configuration
        .GetSection(nameof(DistributedLockOptions))
        .Get<DistributedLockOptions>();

    services.AddApplicationInsightsTelemetry();

    services.AddSingleton<ILeaderElection, LeaderElection>();
    services.AddSingleton<IDistributedLock, DistributedLock>();
    services.AddSingleton(distributedLockOptions);
    services.AddHostedService<DemoBackgroundService>();
}

The background worker can then use the LeaderElection instance to try to become the leader and do its work:

    public class DemoBackgroundService : IHostedService
    {
        private readonly ILogger<BackgroundService> _logger;
        private readonly ILeaderElection _leaderElection;
        private CancellationTokenSource? _cancellationTokenSource;
        private Task _continuousTask = Task.CompletedTask;

        public DemoBackgroundService(ILogger<BackgroundService> logger, ILeaderElection leaderElection)
        {
            _logger = logger;
            _leaderElection = leaderElection;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting DemoBackgroundService");

            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            _continuousTask = _leaderElection.RunTaskWhenElectedLeaderAsync(WorkerAsync, _cancellationTokenSource.Token);

            return Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping DemoBackgroundService");

            _cancellationTokenSource?.Cancel();

            await _continuousTask;
        }

        public async Task WorkerAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                _logger.LogInformation("Working...");
                await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
            }
        }
    }

Implementation

Once RunTaskWhenElectedLeaderAsync is called an attempt is made to acquire a lease on a blob. If it succeeds it will run the specified tasks and keep renewing the lease at the same time. If it fails to acquire a lease it will wait for a specified time before trying to acquire a lease on a blob again.

When the task is cancelled the lease is released. If the process terminates without releasing the lease explicitly it will automatically be release after the specified lease interval has elapsed.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.1 691 10/19/2024
2.0.0 126 10/19/2024
1.5.0 23,910 11/8/2021
1.4.0 563 7/19/2021
1.3.0 482 7/14/2021
1.2.0 457 7/14/2021