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

AsyncLazy will cache the exceptions #19

Open
gravity00 opened this issue Oct 23, 2018 · 3 comments
Open

AsyncLazy will cache the exceptions #19

gravity00 opened this issue Oct 23, 2018 · 3 comments

Comments

@gravity00
Copy link

public class LazyRemoteConnection : IRemoteConnection
{
private readonly AsyncLazy<RemoteConnection> _connectionTask;
public LazyRemoteConnection(RemoteConnectionFactory remoteConnectionFactory)
{
_connectionTask = new AsyncLazy<RemoteConnection>(() => remoteConnectionFactory.ConnectAsync());
}
public async Task PublishAsync(string channel, string message)
{
var connection = await _connectionTask.Value;
await connection.PublishAsync(channel, message);
}
public async Task DisposeAsync()
{
// Don't connect just to dispose
if (!_connectionTask.IsValueCreated)
{
return;
}
var connection = await _connectionTask.Value;
await connection.DisposeAsync();
}
private class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<Task<T>> valueFactory) : base(valueFactory)
{
}
}
}

I believe it should be at least noted that if an exception occurs inside the factory function, the exception will be cached by the Task and since everything is a singleton, the application won't be able to recover from the failed state without some restart (unless I'm missing something).

Obviously this may or may not be a problem, depends on the developer needs, but usually this isn't the intended behavior. Most commonly is like not adding an item to a cache if the initialization fails.

@davidfowl
Copy link
Owner

That doesn’t matter in this case but it does matter for the caching case so I’ll update that.

Thanks for the feedback

@wlidha81
Copy link

Same comment as gravity00, when an exception occurs at the fetch if the value to be cached, exception is cached instead. it might be also needed to handle the case when valueFactory returns (Null OR Default) value that we don't want to cache, in that case cache entry should be disposed rather than being saved as Task that returns null.

@bartelink
Copy link

bartelink commented May 30, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants