2022-07-12 20:12:23 +03:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
|
|
|
|
|
namespace Bit.App.Controls
|
|
|
|
|
{
|
|
|
|
|
public interface IAvatarImageSourcePool
|
|
|
|
|
{
|
2023-01-12 21:27:10 +03:00
|
|
|
|
AvatarImageSource GetOrCreateAvatar(string userId, string name, string email, string color);
|
2022-07-12 20:12:23 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class AvatarImageSourcePool : IAvatarImageSourcePool
|
|
|
|
|
{
|
|
|
|
|
private readonly ConcurrentDictionary<string, AvatarImageSource> _cache = new ConcurrentDictionary<string, AvatarImageSource>();
|
|
|
|
|
|
2023-01-12 21:27:10 +03:00
|
|
|
|
public AvatarImageSource GetOrCreateAvatar(string userId, string name, string email, string color)
|
2022-07-12 20:12:23 +03:00
|
|
|
|
{
|
2023-01-12 21:27:10 +03:00
|
|
|
|
var key = $"{userId}{name}{email}{color}";
|
2022-07-12 20:12:23 +03:00
|
|
|
|
if (!_cache.TryGetValue(key, out var avatar))
|
|
|
|
|
{
|
2023-01-12 21:27:10 +03:00
|
|
|
|
avatar = new AvatarImageSource(userId, name, email, color);
|
2022-07-12 20:12:23 +03:00
|
|
|
|
if (!_cache.TryAdd(key, avatar)
|
|
|
|
|
&&
|
|
|
|
|
!_cache.TryGetValue(key, out avatar)) // If add fails another thread created the avatar in between the first try get and the try add.
|
|
|
|
|
{
|
|
|
|
|
// if add and get after fails, then something wrong is going on with this method.
|
|
|
|
|
throw new InvalidOperationException("Something is wrong creating the avatar image");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return avatar;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|