Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release the AsyncLazy delegate when the result has been obtained. #269

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions src/Nito.AsyncEx.Coordination/AsyncLazy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,6 @@ public sealed class AsyncLazy<T>
/// </summary>
private readonly object _mutex;

/// <summary>
/// The factory method to call.
/// </summary>
private readonly Func<Task<T>> _factory;

/// <summary>
/// The underlying lazy task.
/// </summary>
Expand Down Expand Up @@ -77,14 +72,13 @@ public AsyncLazy(Func<Task<T>> factory, AsyncLazyFlags flags = AsyncLazyFlags.No
{
if (factory == null)
throw new ArgumentNullException(nameof(factory));
_factory = factory;
if ((flags & AsyncLazyFlags.RetryOnFailure) == AsyncLazyFlags.RetryOnFailure)
_factory = RetryOnFailure(_factory);
if ((flags & AsyncLazyFlags.ExecuteOnCallingThread) != AsyncLazyFlags.ExecuteOnCallingThread)
_factory = RunOnThreadPool(_factory);
factory = RunOnThreadPool(factory);
if ((flags & AsyncLazyFlags.RetryOnFailure) == AsyncLazyFlags.RetryOnFailure)
factory = RetryOnFailure(factory);

_mutex = new object();
_instance = new Lazy<Task<T>>(_factory);
_instance = new Lazy<Task<T>>(factory);
}

/// <summary>
Expand Down Expand Up @@ -121,17 +115,18 @@ public Task<T> Task

private Func<Task<T>> RetryOnFailure(Func<Task<T>> factory)
{
return async () =>
var originalFactory = factory;
return factory = async () =>
{
try
{
return await factory().ConfigureAwait(false);
return await originalFactory().ConfigureAwait(false);
}
catch
{
lock (_mutex)
{
_instance = new Lazy<Task<T>>(_factory);
_instance = new Lazy<Task<T>>(factory);
timcassell marked this conversation as resolved.
Show resolved Hide resolved
}
throw;
}
Expand Down