Skip to content

Commit

Permalink
Better readme
Browse files Browse the repository at this point in the history
  • Loading branch information
soenneker committed Jan 8, 2025
1 parent 99338a6 commit 73f692d
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 32 deletions.
99 changes: 71 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,102 @@
[![](https://img.shields.io/nuget/dt/Soenneker.Utils.AsyncSingleton.svg?style=for-the-badge)](https://www.nuget.org/packages/Soenneker.Utils.AsyncSingleton/)

# ![](https://user-images.githubusercontent.com/4441470/224455560-91ed3ee7-f510-4041-a8d2-3fc093025112.png) Soenneker.Utils.AsyncSingleton
### An externally initializing singleton that uses double-check asynchronous locking, with optional async and sync disposal

`AsyncSingleton` is a lightweight utility that provides lazy (and optionally asynchronous) initialization of an instance. It ensures that the instance is only created once, even in highly concurrent scenarios. It also offers both synchronous and asynchronous initialization methods while supporting a variety of initialization signatures. Additionally, `AsyncSingleton` implements both synchronous and asynchronous disposal.

## Features

- **Lazy Initialization**: The instance is created only upon the first call of `Get()`, `GetAsync()`, `Init()` or `InitSync()`.
- **Thread-safe**: Uses asynchronous locking for coordinated initialization in concurrent environments.
- **Multiple Initialization Patterns**:
- Sync and async initialization
- With or without parameters (`params object[]`)
- With or without `CancellationToken`
- **Re-initialization Guard**: Once the singleton is initialized (or has begun initializing), further initialization reconfigurations are disallowed.

## Installation

```
dotnet add package Soenneker.Utils.AsyncSingleton
```

## Example
There are two different types: `AsyncSingleton`, and `AsyncSingleton<T>`:

The example below is a long-living `HttpClient` implementation using `AsyncSingleton`. It avoids the additional overhead of `IHttpClientFactory`, and doesn't rely on short-lived clients.
### `AsyncSingleton<T>`
Useful in scenarios where you need a result of the initialization. `Get()` is the primary method.

```csharp
public class HttpRequester : IDisposable, IAsyncDisposable
using Microsoft.Extensions.Logging;

public class MyService
{
private readonly AsyncSingleton<HttpClient> _client;
private readonly ILogger<MyService> _logger;
private readonly AsyncSingleton<HttpClient> _asyncSingleton;

public HttpRequester()
public MyService(ILogger<MyService> logger)
{
// This func will lazily execute once it's retrieved the first time.
// Other threads calling this at the same moment will asynchronously wait,
// and then utilize the HttpClient that was created from the first caller.
_client = new AsyncSingleton<HttpClient>(() =>
_logger = logger;

_asyncSingleton = new AsyncSingleton(async () =>
{
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
MaxConnectionsPerServer = 10
};
_logger.LogInformation("Initializing the singleton resource synchronously...");
await Task.Delay(1000);

return new HttpClient(socketsHandler);
return new HttpClient();
});
}

public async ValueTask Get()
public async ValueTask StartWork()
{
// retrieve the singleton async, thus not blocking the calling thread
await (await _client.Get()).GetAsync("https://google.com");
var httpClient = await _asyncSingleton.Get();

// At this point the task has been run, guaranteed only once (no matter if this is called concurrently)
var sameHttpClient = await _asyncSingleton.Get(); // This is the same instance of the httpClient above
}
}
```

// Disposal is not necessary for AsyncSingleton unless the type used is IDisposable/IAsyncDisposable
public ValueTask DisposeAsync()
### `AsyncSingleton`
Useful in scenarios where you just need async single initialization, and you don't ever need to leverage an instance. `Init()` is the primary method.

```csharp
using Microsoft.Extensions.Logging;

public class MyService
{
private readonly ILogger<MyService> _logger;
private readonly AsyncSingleton _singleExecution;

public MyService(ILogger<MyService> logger)
{
GC.SuppressFinalize(this);
_logger = logger;

_singleExecution = new AsyncSingleton(async () =>
{
_logger.LogInformation("Initializing the singleton resource ...");
await Task.Delay(1000); // Simulates an async call
return _client.DisposeAsync();
return new object(); // This object is needed for AsyncSingleton to recognize that initialization has occurred
});
}

public void Dispose()
public async ValueTask StartWork()
{
GC.SuppressFinalize(this);

_client.Dispose();
await _singleExecution.Init();

// At this point the task has been run, guaranteed only once (no matter if this is called concurrently)
await _singleExecution.Init(); // This will NOT execute the task, since it's already been called
}
}
```
```

Tips:
- If you need to cancel the initialization, pass a `CancellationToken` to the `Init()`, and `Get()` method. This will cancel any locking occurring during initialization.
- If you use a type of `AsyncSingleton` that implements `IDisposable` or `IAsyncDisposable`, be sure to dispose of the `AsyncSingleton` instance. This will dispose the underlying instance.
- Be careful about updating the underlying instance directly, as `AsyncSingleton` holds a reference to it, and will return those changes to further callers.
- `SetInitialization()` can be used to set the initialization function after the `AsyncSingleton` has been created. This can be useful in scenarios where the initialization function is not known at the time of creation.
- Try not to use an asynchronous initialization method, and then retrieve it synchronously. If you do so, `AsyncSingleton` will block to maintain thread-safety.
- Using a synchronous initialization method with asynchronous retrieval will not block, and will still provide thread-safety.
- Similarly, if the underlying instance is `IAsyncDisposable`, try to leverage `AsyncSingleton.DisposeAsync()`. Using `AsyncSingleton.DisposeAsync()` with an `IDisposable` underlying instance is fine.
4 changes: 2 additions & 2 deletions src/Abstract/IAsyncSingleton.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable
/// <remarks>The initialization func needs to be set before calling this, either in the ctor or via the other methods</remarks>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="NullReferenceException"></exception>
ValueTask Init(CancellationToken cancellationToken, object[] objects);
ValueTask Init(CancellationToken cancellationToken, params object[] objects);

/// <summary>
/// <see cref="Init(System.Threading.CancellationToken,object[])"/> should be used instead of this if possible. This method can block the calling thread! It's lazy; it's initialized only when retrieving. <para/>
Expand All @@ -44,7 +44,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable
/// <remarks>The initialization func needs to be set before calling this, either in the ctor or via the other methods</remarks>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="NullReferenceException"></exception>
void InitSync(CancellationToken cancellationToken, object[] objects);
void InitSync(CancellationToken cancellationToken, params object[] objects);

/// <see cref="SetInitialization(Func{object})"/>
void SetInitialization(Func<CancellationToken, object[], ValueTask<object>> func);
Expand Down
4 changes: 2 additions & 2 deletions src/Abstract/IAsyncSingleton{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public interface IAsyncSingleton<T> : IDisposable, IAsyncDisposable
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="NullReferenceException"></exception>
[Pure]
ValueTask<T> Get(CancellationToken cancellationToken, object[] objects);
ValueTask<T> Get(CancellationToken cancellationToken, params object[] objects);

/// <summary>
/// <see cref="Get"/> should be used instead of this if possible. This method can block the calling thread! It's lazy; it's initialized only when retrieving. <para/>

Check warning on line 35 in src/Abstract/IAsyncSingleton{T}.cs

View workflow job for this annotation

GitHub Actions / publish-package

Ambiguous reference in cref attribute: 'Get'. Assuming 'IAsyncSingleton<T>.Get(object[])', but could have also matched other overloads including 'IAsyncSingleton<T>.Get(CancellationToken, params object[])'.
Expand All @@ -49,7 +49,7 @@ public interface IAsyncSingleton<T> : IDisposable, IAsyncDisposable
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="NullReferenceException"></exception>
[Pure]
T GetSync(CancellationToken cancellationToken, object[] objects);
T GetSync(CancellationToken cancellationToken, params object[] objects);

/// <see cref="SetInitialization(Func{T})"/>
void SetInitialization(Func<CancellationToken, object[], ValueTask<T>> func);
Expand Down
1 change: 1 addition & 0 deletions src/AsyncSingleton{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Soenneker.Utils.AsyncSingleton;

///<inheritdoc cref="IAsyncSingleton{T}"/>
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class AsyncSingleton<T> : IAsyncSingleton<T>
{
private T? _instance;
Expand Down

0 comments on commit 73f692d

Please sign in to comment.