From 73f692d4827b859057ef6ddb1c3736e987e29c0d Mon Sep 17 00:00:00 2001 From: Jake Soenneker Date: Wed, 8 Jan 2025 10:34:30 -0600 Subject: [PATCH] Better readme --- README.md | 99 +++++++++++++++++++++--------- src/Abstract/IAsyncSingleton.cs | 4 +- src/Abstract/IAsyncSingleton{T}.cs | 4 +- src/AsyncSingleton{T}.cs | 1 + 4 files changed, 76 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 47ca525..319fcdf 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,18 @@ [![](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 @@ -11,51 +22,83 @@ dotnet add package Soenneker.Utils.AsyncSingleton ``` -## Example +There are two different types: `AsyncSingleton`, and `AsyncSingleton`: -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` +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 _client; + private readonly ILogger _logger; + private readonly AsyncSingleton _asyncSingleton; - public HttpRequester() + public MyService(ILogger 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(() => + _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 _logger; + private readonly AsyncSingleton _singleExecution; + + public MyService(ILogger 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 } } -``` \ No newline at end of file +``` + +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. \ No newline at end of file diff --git a/src/Abstract/IAsyncSingleton.cs b/src/Abstract/IAsyncSingleton.cs index 7398606..0dc1e34 100644 --- a/src/Abstract/IAsyncSingleton.cs +++ b/src/Abstract/IAsyncSingleton.cs @@ -26,7 +26,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable /// The initialization func needs to be set before calling this, either in the ctor or via the other methods /// /// - ValueTask Init(CancellationToken cancellationToken, object[] objects); + ValueTask Init(CancellationToken cancellationToken, params object[] objects); /// /// should be used instead of this if possible. This method can block the calling thread! It's lazy; it's initialized only when retrieving. @@ -44,7 +44,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable /// The initialization func needs to be set before calling this, either in the ctor or via the other methods /// /// - void InitSync(CancellationToken cancellationToken, object[] objects); + void InitSync(CancellationToken cancellationToken, params object[] objects); /// void SetInitialization(Func> func); diff --git a/src/Abstract/IAsyncSingleton{T}.cs b/src/Abstract/IAsyncSingleton{T}.cs index f559407..b606049 100644 --- a/src/Abstract/IAsyncSingleton{T}.cs +++ b/src/Abstract/IAsyncSingleton{T}.cs @@ -29,7 +29,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable /// /// [Pure] - ValueTask Get(CancellationToken cancellationToken, object[] objects); + ValueTask Get(CancellationToken cancellationToken, params object[] objects); /// /// should be used instead of this if possible. This method can block the calling thread! It's lazy; it's initialized only when retrieving. @@ -49,7 +49,7 @@ public interface IAsyncSingleton : IDisposable, IAsyncDisposable /// /// [Pure] - T GetSync(CancellationToken cancellationToken, object[] objects); + T GetSync(CancellationToken cancellationToken, params object[] objects); /// void SetInitialization(Func> func); diff --git a/src/AsyncSingleton{T}.cs b/src/AsyncSingleton{T}.cs index d5e110a..4e2d60b 100644 --- a/src/AsyncSingleton{T}.cs +++ b/src/AsyncSingleton{T}.cs @@ -9,6 +9,7 @@ namespace Soenneker.Utils.AsyncSingleton; /// +// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class AsyncSingleton : IAsyncSingleton { private T? _instance;