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

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

Susan Sarandon
Release: 2025-01-13 21:49:43
Original
272 people have browsed it

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

Ensuring Single Execution of Asynchronous Initialization in C#

In asynchronous programming, it's essential to guarantee that initialization procedures run only once. Imagine a class needing asynchronous initialization via an InitializeAsync() method. Preventing multiple threads from simultaneously calling this method is key. While SemaphoreSlim could be used, more efficient and elegant methods exist.

AsyncLazy: A Streamlined Solution

AsyncLazy, an extension of the standard .NET Lazy class, is designed for asynchronous initialization. It offers a simple and effective solution.

<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>
Copy after login

Using AsyncLazy is straightforward. Instantiate it, providing your asynchronous initialization logic:

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

Summary

AsyncLazy provides a robust and user-friendly method for ensuring single execution of asynchronous initialization. Its simplicity makes it ideal for preventing concurrent calls to critical initialization functions.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template