如何将单个 属性 更改为值字典?
How to change a single property to a dictionary of values?
我有这个 属性:
private static Lazy<TimeLimiter> rateLimiter = new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval));
public static TimeLimiter RateLimiter => rateLimiter.Value;
当我第一次访问它时,它被初始化了。
问题是,我不想为不同的客户端设置 RateLimiter1
、 RateLimiter2
等多个实例,而是想更改它以便它适用于多个客户端。也许使用 dictionary
和 client1
、client2
等字符串键
但是我不知道上面第一行字典中的每个键到底是如何初始化的。有小费吗?谢谢。
(对不起标题,想不出更好的描述:)))
是这样的吗?
private static Dictionary<string, Lazy<TimeLimiter>> rateLimiters = new Dictionary<string, Lazy<TimeLimiter>>();
public static TimeLimiter GetRateLimiterForClient(string clientId)
{
if (!rateLimiters.ContainsKey(clientId))
{
rateLimiters.Add(clientId,
new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval)));
}
return rateLimiters[clientId].Value;
}
线程安全的解决方案(如果被多个客户端使用,通常是必需的)类似于:
private static ConcurrentDictionary<string, Lazy<TimeLimiter>> ratelimiters = new ConcurrentDictionary<string, Lazy<TimeLimiter>>();
public static TimeLimiter GetRateLimiterForClient(string clientId)
{
return ratelimiters.GetOrAdd(clientId, c =>
new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval)))
.Value;
}
ConcurrentDictionary
的 GetOrAdd
将 return 现有的 Lazy
(如果存在),或者 Add
一个新的(如果需要)。 .Value
然后将从 Lazy
中得到 TimeLimiter
。
我有这个 属性:
private static Lazy<TimeLimiter> rateLimiter = new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval));
public static TimeLimiter RateLimiter => rateLimiter.Value;
当我第一次访问它时,它被初始化了。
问题是,我不想为不同的客户端设置 RateLimiter1
、 RateLimiter2
等多个实例,而是想更改它以便它适用于多个客户端。也许使用 dictionary
和 client1
、client2
等字符串键
但是我不知道上面第一行字典中的每个键到底是如何初始化的。有小费吗?谢谢。
(对不起标题,想不出更好的描述:)))
是这样的吗?
private static Dictionary<string, Lazy<TimeLimiter>> rateLimiters = new Dictionary<string, Lazy<TimeLimiter>>();
public static TimeLimiter GetRateLimiterForClient(string clientId)
{
if (!rateLimiters.ContainsKey(clientId))
{
rateLimiters.Add(clientId,
new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval)));
}
return rateLimiters[clientId].Value;
}
线程安全的解决方案(如果被多个客户端使用,通常是必需的)类似于:
private static ConcurrentDictionary<string, Lazy<TimeLimiter>> ratelimiters = new ConcurrentDictionary<string, Lazy<TimeLimiter>>();
public static TimeLimiter GetRateLimiterForClient(string clientId)
{
return ratelimiters.GetOrAdd(clientId, c =>
new Lazy<TimeLimiter>(() =>
TimeLimiter.GetFromMaxCountByInterval(MaxCount, Interval)))
.Value;
}
ConcurrentDictionary
的 GetOrAdd
将 return 现有的 Lazy
(如果存在),或者 Add
一个新的(如果需要)。 .Value
然后将从 Lazy
中得到 TimeLimiter
。