using System.Threading.Tasks;
public class AsyncLazyCustom<T>
private readonly Func<Task<T>> _factory;
private bool _initialized;
public AsyncLazyCustom(Func<Task<T>> factory)
public async Task<T> Value()
return await LazyInitializer.EnsureInitialized(ref _task, ref _initialized, ref _lock, _factory);
Volatile.Write(ref _initialized, false);
public class CachingKeyVaultCertificateAuthorityProvider
private readonly AsyncLazyCustom<string> _certificateAuthorityLazy;
public bool ThrowException { get; set; } = true;
public CachingKeyVaultCertificateAuthorityProvider()
_certificateAuthorityLazy = new AsyncLazyCustom<string>(
async () => await GetCertificateAuthorityInternalAsync().ConfigureAwait(false));
public Task<string> GetCertificateAuthorityAsync()
return _certificateAuthorityLazy.Value();
internal async Task<string> GetCertificateAuthorityInternalAsync()
throw new Exception("exception was thrown");
return await Task.FromResult("this is the certificate");
public static void Main()
CachingKeyVaultCertificateAuthorityProvider provider = new CachingKeyVaultCertificateAuthorityProvider();
Console.WriteLine("throw exception: " + provider.ThrowException);
TryLogCertificateAuthority(provider);
provider.ThrowException = false;
Console.WriteLine("throw exception: " + provider.ThrowException);
TryLogCertificateAuthority(provider);
public static void TryLogCertificateAuthority(CachingKeyVaultCertificateAuthorityProvider provider)
string cert = provider.GetCertificateAuthorityAsync().GetAwaiter().GetResult();
Console.WriteLine(ex.Message);