gpt4 book ai didi

c# - 带有过期时间的 Lazy

转载 作者:可可西里 更新时间:2023-11-01 09:10:10 25 4
gpt4 key购买 nike

我想在惰性对象上实现过期时间。过期冷却时间必须从第一次检索值开始。如果我们得到该值,并且过期时间已过,那么我们重新执行该函数并重置过期时间。

我不熟悉扩展、部分关键字,我不知道最好的方法。

谢谢

编辑:

到目前为止的代码:

新编辑:

新代码:

public class LazyWithExpiration<T>
{
private volatile bool expired;
private TimeSpan expirationTime;
private Func<T> func;
private Lazy<T> lazyObject;

public LazyWithExpiration( Func<T> func, TimeSpan expirationTime )
{
this.expirationTime = expirationTime;
this.func = func;

Reset();
}

public void Reset()
{
lazyObject = new Lazy<T>( func );
expired = false;
}

public T Value
{
get
{
if ( expired )
Reset();

if ( !lazyObject.IsValueCreated )
{
Task.Factory.StartNew( () =>
{
Thread.Sleep( expirationTime );
expired = true;
} );
}

return lazyObject.Value;
}
}

}

最佳答案

2021 年编辑:

您可能不应该使用此代码。也许对于一个非常简单的应用程序来说已经足够好了,但是它有一些问题。它不支持缓存失效,由于它使用 DateTime 的方式,它可能会出现与 DST 或其他时区更改相关的问题,并且它以一种安全但可能非常慢的方式使用锁。考虑使用类似 MemoryCache 的东西相反。

原答案:

我同意其他评论者的观点,您可能根本不应该接触 Lazy。如果您忽略多个线程安全选项,惰性并不是很复杂,所以只需从头开始实现它。

顺便说一句,我非常喜欢这个想法,尽管我不知道我是否愿意将它用作通用缓存策略。对于一些更简单的场景,这可能就足够了。

这是我的尝试。如果你不需要它是线程安全的,你可以删除锁定的东西。我认为这里不可能使用双重检查锁模式,因为缓存值可能会在锁内失效。

public class Temporary<T>
{
private readonly Func<T> factory;
private readonly TimeSpan lifetime;
private readonly object valueLock = new object();

private T value;
private bool hasValue;
private DateTime creationTime;

public Temporary(Func<T> factory, TimeSpan lifetime)
{
this.factory = factory;
this.lifetime = lifetime;
}

public T Value
{
get
{
DateTime now = DateTime.Now;
lock (this.valueLock)
{
if (this.hasValue)
{
if (this.creationTime.Add(this.lifetime) < now)
{
this.hasValue = false;
}
}

if (!this.hasValue)
{
this.value = this.factory();
this.hasValue = true;

// You can also use the existing "now" variable here.
// It depends on when you want the cache time to start
// counting from.
this.creationTime = Datetime.Now;
}

return this.value;
}
}
}
}

关于c# - 带有过期时间的 Lazy<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18685134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com