C# 使用属性缓存方法';s返回C中的结果#
在webmethods中,通过注释[WebMethod(CacheDuration…]属性来实现缓存非常简单。我们可以为非webmethods(例如静态方法)创建类似的内容吗C# 使用属性缓存方法';s返回C中的结果#,c#,.net,caching,attributes,C#,.net,Caching,Attributes,在webmethods中,通过注释[WebMethod(CacheDuration…]属性来实现缓存非常简单。我们可以为非webmethods(例如静态方法)创建类似的内容吗 非常感谢您提供的任何帮助/提示。没有任何内置功能可以准确实现您想要的功能。您应该使用Httpruntime.Cache 它不是一个内置的特性,但您可以使用面向方面编程(AOP)实现类似的功能。使用方面缓存信息 如果你有兴趣提供AOP如果你不能使用AOP来完成工作,你可以尝试使用我创建的这个小类 public MyClass
非常感谢您提供的任何帮助/提示。没有任何内置功能可以准确实现您想要的功能。您应该使用
Httpruntime.Cache
它不是一个内置的特性,但您可以使用面向方面编程(AOP)实现类似的功能。使用方面缓存信息
如果你有兴趣提供AOP如果你不能使用AOP来完成工作,你可以尝试使用我创建的这个小类
public MyClass CachedInstance
{
get { return _cachedInstance.Value; }
}
private static readonly Cached<MyClass> _cachedInstance = new Cached<MyClass>(() => new MyClass(), TimeSpan.FromMinutes(15));
public sealed class Cached<T>
{
private readonly Func<T> _createValue;
private readonly TimeSpan _cacheFor;
private DateTime _createdAt;
private T _value;
public T Value
{
get
{
if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
{
lock (this)
{
if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
{
_value = _createValue();
_createdAt = DateTime.Now;
}
}
}
return _value;
}
}
public Cached(Func<T> createValue, TimeSpan cacheFor)
{
if (createValue == null)
{
throw new ArgumentNullException("createValue");
}
_createValue = createValue;
_cacheFor = cacheFor;
}
}
公共MyClass缓存状态
{
获取{return\u cachedInstance.Value;}
}
private static readonly Cached_cachedInstance=new Cached(()=>new MyClass(),TimeSpan.frommins(15));
缓存的公共密封类
{
私有只读函数_createValue;
专用只读TimeSpan\u cacheFor;
私有日期时间_createdAt;
私人T_值;
公共价值
{
得到
{
如果(_createdAt==DateTime.MinValue | | DateTime.Now-_createdAt>_cacheFor)
{
锁(这个)
{
如果(_createdAt==DateTime.MinValue | | DateTime.Now-_createdAt>_cacheFor)
{
_值=_createValue();
_createdAt=DateTime.Now;
}
}
}
返回_值;
}
}
公共缓存(Func createValue,TimeSpan cacheFor)
{
if(createValue==null)
{
抛出新ArgumentNullException(“createValue”);
}
_createValue=createValue;
_cacheFor=cacheFor;
}
}
使用Post Sharp检查缓存属性的简单实现。我很好奇为什么。我不相信这是可能的。Alastair,原因是我不想让缓存实现在方法中无处不在。其次,我有一堆静态方法(没有静态成员或上下文)因此,为每一个实现缓存都是非常耗时和混乱的。我想我只是在寻找一种简单的方法。面向方面的编程肯定会有帮助!谢谢大家。@SP。你有没有提出任何声明性的捕获解决方案?谢谢你的回复,Claudio.AoP可以帮上忙,但目前项目不可能。所以t其次是属性。我们不能继续使用HttpRuntime.Cache和属性吗?如果是这样,有什么关于如何实现它的建议吗?@SP:恐怕你必须通过编程来实现,你不能使用属性。@SP属性只不过是嵌入在程序集中的元数据。你需要一些东西来读取元数据并拦截方法调用。这正是AOP所做的。因此,仅属性的解决方案是不可能的。谢谢,看起来我必须研究AOP框架。但这将是值得的。谢谢!PostSharp非常棒,完全符合我的要求。非常好的商业替代方案。谢谢你,Fernando。我正在寻找更具声明性的缓存方式,因此AOP解决方案更适合。如果每件事都失败了,我不得不用艰难的方式去做,留下到处都是的内脏。乱七八糟!