Home >Backend Development >C++ >How Can I Ensure Single Execution of Asynchronous Initialization Methods in C#?

How Can I Ensure Single Execution of Asynchronous Initialization Methods in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-13 21:48:42606browse

How Can I Ensure Single Execution of Asynchronous Initialization Methods in C#?

Single Execution of Asynchronous Initialization Methods in C#

In C# development, ensuring that asynchronous initialization methods execute only once is critical. This prevents race conditions where multiple threads concurrently attempt the same initialization, leading to potential errors. While SemaphoreSlim provides a solution, AsyncLazy<T> from the Microsoft.Extensions.Primitives package offers a more elegant and efficient approach.

Leveraging AsyncLazy

AsyncLazy<T> provides lazy initialization for asynchronous operations. It encapsulates an asynchronous task, allowing you to await its completion using GetAwaiter(). A slightly modified AsyncLazy<T> class is shown below:

<code class="language-csharp">public class AsyncLazy<T> : Lazy<Task<T>>
{
    public AsyncLazy(Func<T> valueFactory) :
        base(() => Task.Run(valueFactory)) { }

    public AsyncLazy(Func<Task<T>> taskFactory) :
        base(() => Task.Run(() => taskFactory())) { }

    public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}</code>

Practical Application

Using AsyncLazy<T> is straightforward. Instantiate it with your initialization logic as a lambda expression:

<code class="language-csharp">private AsyncLazy<bool> asyncLazy = new AsyncLazy<bool>(async () =>
{
    await DoStuffOnlyOnceAsync();
    return true;
});</code>

To execute the initialization, simply await the asyncLazy object:

<code class="language-csharp">await asyncLazy;</code>

Summary

AsyncLazy<T> provides a clean and efficient mechanism for ensuring single execution of asynchronous initialization methods. It simplifies development by eliminating the complexities of manual locking or semaphore management, resulting in more readable and maintainable code.

The above is the detailed content of How Can I Ensure Single Execution of Asynchronous Initialization Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn