Is there anyway to cache function/method in C#
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I got bored with writing same to code again and again to cache the objects in data access layer.
Is there anyway to cache c# function results without much changes to functions.
Is there any framework supports this functionality at the moment?
Can i archive the same by writing custom "c# function attributes"? if so, drop me some points to start implementation?
c# .net
add a comment |
I got bored with writing same to code again and again to cache the objects in data access layer.
Is there anyway to cache c# function results without much changes to functions.
Is there any framework supports this functionality at the moment?
Can i archive the same by writing custom "c# function attributes"? if so, drop me some points to start implementation?
c# .net
3
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17
add a comment |
I got bored with writing same to code again and again to cache the objects in data access layer.
Is there anyway to cache c# function results without much changes to functions.
Is there any framework supports this functionality at the moment?
Can i archive the same by writing custom "c# function attributes"? if so, drop me some points to start implementation?
c# .net
I got bored with writing same to code again and again to cache the objects in data access layer.
Is there anyway to cache c# function results without much changes to functions.
Is there any framework supports this functionality at the moment?
Can i archive the same by writing custom "c# function attributes"? if so, drop me some points to start implementation?
c# .net
c# .net
asked Feb 8 '11 at 4:28
VeeruVeeru
1302214
1302214
3
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17
add a comment |
3
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17
3
3
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17
add a comment |
7 Answers
7
active
oldest
votes
You can create caching attributes with PostSharp. Here is an example.
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
add a comment |
Possibility 1: Use IL Weaving
Postsharp was mentioned before.
You could also try the MethodCache.Fody package.
Possibility 2: Use an Proxy / Interception Framework
Example (Ninject & Ninject.Interception):
public class CacheAttribute : InterceptAttribute
public override IInterceptor CreateInterceptor(IProxyRequest request)
return request.Context.Kernel.Get<CachingInterceptor>();
public class CachingInterceptor : IInterceptor
private ICache Cache get; set;
public CachingInterceptor(ICache cache)
Cache = cache;
public void Intercept(IInvocation invocation)
string className = invocation.Request.Target.GetType().FullName;
string methodName = invocation.Request.Method.Name;
object arguments = invocation.Request.Arguments;
StringBuilder builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
arguments.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
object retrieve = Cache.Retrieve<object>(cacheKey);
if (retrieve == null)
invocation.Proceed();
retrieve = invocation.ReturnValue;
Cache.Store(cacheKey, retrieve);
else
invocation.ReturnValue = retrieve;
Then you could decorate functions like this:
[Cache]
public virtual Customer GetCustomerByID(int customerID)
return CustomerRepository.GetCustomerByID(customerID);
Intercepted functions have to be virtual and classes must be created by the Ninject kernel. If you rely on performance, you could proxy classes directly via Castle.DynamicProxy (which is internally used by Ninject.Extensions.Interception.DynamicProxy).
Possibility 3: Use an Expression wrapper
You could pass the function as expression, generate a caching key containing class, method and parameter information and invoke the expression if not found in your Cache. This adds more runtime overhead than AOP / Proxy frameworks, but will be sufficient for simple solutions.
private T CacheAction<T>(Expression<Func<T>> action, [CallerMemberName] string memberName = "") where T : class
MethodCallExpression body = (MethodCallExpression)action.Body;
ICollection<object> parameters = new List<object>();
foreach (MemberExpression expression in body.Arguments)
parameters.Add(((FieldInfo)expression.Member).GetValue(((ConstantExpression)expression.Expression).Value));
StringBuilder builder = new StringBuilder(100);
builder.Append(GetType().FullName);
builder.Append(".");
builder.Append(memberName);
parameters.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
T retrieve = Cache.Retrieve<T>(cacheKey);
if (retrieve == null)
retrieve = action.Compile().Invoke();
Cache.Store(cacheKey, retrieve);
return retrieve;
public Customer GetCustomerByID(int customerID)
return CacheAction(() => CustomerRepository.GetCustomerByID(customerID));
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
add a comment |
If I read you question correct, the right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it.
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
add a comment |
The Cache Application block is Microsoft's answer to built in library for Caching in .NET.
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
add a comment |
Lazy store it's value after first run.
Example: http://msdn.microsoft.com/en-us/vstudio/bb870976
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
add a comment |
I suggest Spring.Net AOP.
It basically creates a proxy and the calls can be redirected from/to the cache.
http://www.springframework.net/doc/reference/html/aop-quickstart.html
and then you can have something like that for your advice:
public class CachingAroundAdvice : IMethodInterceptor
{
#region Variable Declarations
private Priority priority = Priority.Normal;
#endregion
public object Invoke(IMethodInvocation invocation)
// declare local variables
string cacheKey = string.Empty;
object dataObject = null;
// build cache key with some algorithm
cacheKey = CreateCacheKey(invocation.Method, invocation.Arguments);
// retrieve item from cache
dataObject = CacheManager.Cache.GetData(cacheKey);
// if the dataobject is not in cache proceed to retrieve it
if (null == dataObject)
dataObject = invocation.Proceed();
// add item to cache
CacheManager.Cache.Add(cacheKey, dataObject, CachePriority, null, Expiration);
// return data object
return dataObject;
add a comment |
I use this simple implementation of the System.Runetime.Caching namespace:
public class InMemoryCache : ICacheService
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(4));
return item;
public void Clear(string cacheKey)
MemoryCache.Default.Remove(cacheKey);
interface ICacheService
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
void Clear(string cacheKey);
Can be used in the following manner:
var cacheProvider = new InMemoryCache();
var cachedResult = cacheProvider.GetOrSet("YourCacheKey",
() => MethodToCache());
First call to the method will cache the result, the next call will return the cached result.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4929540%2fis-there-anyway-to-cache-function-method-in-c-sharp%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can create caching attributes with PostSharp. Here is an example.
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
add a comment |
You can create caching attributes with PostSharp. Here is an example.
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
add a comment |
You can create caching attributes with PostSharp. Here is an example.
You can create caching attributes with PostSharp. Here is an example.
answered Feb 8 '11 at 4:31
Yuriy FaktorovichYuriy Faktorovich
54.3k1190126
54.3k1190126
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
add a comment |
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
Thanks, this is what i'm exactly looking for
– Veeru
Feb 8 '11 at 6:14
add a comment |
Possibility 1: Use IL Weaving
Postsharp was mentioned before.
You could also try the MethodCache.Fody package.
Possibility 2: Use an Proxy / Interception Framework
Example (Ninject & Ninject.Interception):
public class CacheAttribute : InterceptAttribute
public override IInterceptor CreateInterceptor(IProxyRequest request)
return request.Context.Kernel.Get<CachingInterceptor>();
public class CachingInterceptor : IInterceptor
private ICache Cache get; set;
public CachingInterceptor(ICache cache)
Cache = cache;
public void Intercept(IInvocation invocation)
string className = invocation.Request.Target.GetType().FullName;
string methodName = invocation.Request.Method.Name;
object arguments = invocation.Request.Arguments;
StringBuilder builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
arguments.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
object retrieve = Cache.Retrieve<object>(cacheKey);
if (retrieve == null)
invocation.Proceed();
retrieve = invocation.ReturnValue;
Cache.Store(cacheKey, retrieve);
else
invocation.ReturnValue = retrieve;
Then you could decorate functions like this:
[Cache]
public virtual Customer GetCustomerByID(int customerID)
return CustomerRepository.GetCustomerByID(customerID);
Intercepted functions have to be virtual and classes must be created by the Ninject kernel. If you rely on performance, you could proxy classes directly via Castle.DynamicProxy (which is internally used by Ninject.Extensions.Interception.DynamicProxy).
Possibility 3: Use an Expression wrapper
You could pass the function as expression, generate a caching key containing class, method and parameter information and invoke the expression if not found in your Cache. This adds more runtime overhead than AOP / Proxy frameworks, but will be sufficient for simple solutions.
private T CacheAction<T>(Expression<Func<T>> action, [CallerMemberName] string memberName = "") where T : class
MethodCallExpression body = (MethodCallExpression)action.Body;
ICollection<object> parameters = new List<object>();
foreach (MemberExpression expression in body.Arguments)
parameters.Add(((FieldInfo)expression.Member).GetValue(((ConstantExpression)expression.Expression).Value));
StringBuilder builder = new StringBuilder(100);
builder.Append(GetType().FullName);
builder.Append(".");
builder.Append(memberName);
parameters.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
T retrieve = Cache.Retrieve<T>(cacheKey);
if (retrieve == null)
retrieve = action.Compile().Invoke();
Cache.Store(cacheKey, retrieve);
return retrieve;
public Customer GetCustomerByID(int customerID)
return CacheAction(() => CustomerRepository.GetCustomerByID(customerID));
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
add a comment |
Possibility 1: Use IL Weaving
Postsharp was mentioned before.
You could also try the MethodCache.Fody package.
Possibility 2: Use an Proxy / Interception Framework
Example (Ninject & Ninject.Interception):
public class CacheAttribute : InterceptAttribute
public override IInterceptor CreateInterceptor(IProxyRequest request)
return request.Context.Kernel.Get<CachingInterceptor>();
public class CachingInterceptor : IInterceptor
private ICache Cache get; set;
public CachingInterceptor(ICache cache)
Cache = cache;
public void Intercept(IInvocation invocation)
string className = invocation.Request.Target.GetType().FullName;
string methodName = invocation.Request.Method.Name;
object arguments = invocation.Request.Arguments;
StringBuilder builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
arguments.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
object retrieve = Cache.Retrieve<object>(cacheKey);
if (retrieve == null)
invocation.Proceed();
retrieve = invocation.ReturnValue;
Cache.Store(cacheKey, retrieve);
else
invocation.ReturnValue = retrieve;
Then you could decorate functions like this:
[Cache]
public virtual Customer GetCustomerByID(int customerID)
return CustomerRepository.GetCustomerByID(customerID);
Intercepted functions have to be virtual and classes must be created by the Ninject kernel. If you rely on performance, you could proxy classes directly via Castle.DynamicProxy (which is internally used by Ninject.Extensions.Interception.DynamicProxy).
Possibility 3: Use an Expression wrapper
You could pass the function as expression, generate a caching key containing class, method and parameter information and invoke the expression if not found in your Cache. This adds more runtime overhead than AOP / Proxy frameworks, but will be sufficient for simple solutions.
private T CacheAction<T>(Expression<Func<T>> action, [CallerMemberName] string memberName = "") where T : class
MethodCallExpression body = (MethodCallExpression)action.Body;
ICollection<object> parameters = new List<object>();
foreach (MemberExpression expression in body.Arguments)
parameters.Add(((FieldInfo)expression.Member).GetValue(((ConstantExpression)expression.Expression).Value));
StringBuilder builder = new StringBuilder(100);
builder.Append(GetType().FullName);
builder.Append(".");
builder.Append(memberName);
parameters.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
T retrieve = Cache.Retrieve<T>(cacheKey);
if (retrieve == null)
retrieve = action.Compile().Invoke();
Cache.Store(cacheKey, retrieve);
return retrieve;
public Customer GetCustomerByID(int customerID)
return CacheAction(() => CustomerRepository.GetCustomerByID(customerID));
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
add a comment |
Possibility 1: Use IL Weaving
Postsharp was mentioned before.
You could also try the MethodCache.Fody package.
Possibility 2: Use an Proxy / Interception Framework
Example (Ninject & Ninject.Interception):
public class CacheAttribute : InterceptAttribute
public override IInterceptor CreateInterceptor(IProxyRequest request)
return request.Context.Kernel.Get<CachingInterceptor>();
public class CachingInterceptor : IInterceptor
private ICache Cache get; set;
public CachingInterceptor(ICache cache)
Cache = cache;
public void Intercept(IInvocation invocation)
string className = invocation.Request.Target.GetType().FullName;
string methodName = invocation.Request.Method.Name;
object arguments = invocation.Request.Arguments;
StringBuilder builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
arguments.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
object retrieve = Cache.Retrieve<object>(cacheKey);
if (retrieve == null)
invocation.Proceed();
retrieve = invocation.ReturnValue;
Cache.Store(cacheKey, retrieve);
else
invocation.ReturnValue = retrieve;
Then you could decorate functions like this:
[Cache]
public virtual Customer GetCustomerByID(int customerID)
return CustomerRepository.GetCustomerByID(customerID);
Intercepted functions have to be virtual and classes must be created by the Ninject kernel. If you rely on performance, you could proxy classes directly via Castle.DynamicProxy (which is internally used by Ninject.Extensions.Interception.DynamicProxy).
Possibility 3: Use an Expression wrapper
You could pass the function as expression, generate a caching key containing class, method and parameter information and invoke the expression if not found in your Cache. This adds more runtime overhead than AOP / Proxy frameworks, but will be sufficient for simple solutions.
private T CacheAction<T>(Expression<Func<T>> action, [CallerMemberName] string memberName = "") where T : class
MethodCallExpression body = (MethodCallExpression)action.Body;
ICollection<object> parameters = new List<object>();
foreach (MemberExpression expression in body.Arguments)
parameters.Add(((FieldInfo)expression.Member).GetValue(((ConstantExpression)expression.Expression).Value));
StringBuilder builder = new StringBuilder(100);
builder.Append(GetType().FullName);
builder.Append(".");
builder.Append(memberName);
parameters.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
T retrieve = Cache.Retrieve<T>(cacheKey);
if (retrieve == null)
retrieve = action.Compile().Invoke();
Cache.Store(cacheKey, retrieve);
return retrieve;
public Customer GetCustomerByID(int customerID)
return CacheAction(() => CustomerRepository.GetCustomerByID(customerID));
Possibility 1: Use IL Weaving
Postsharp was mentioned before.
You could also try the MethodCache.Fody package.
Possibility 2: Use an Proxy / Interception Framework
Example (Ninject & Ninject.Interception):
public class CacheAttribute : InterceptAttribute
public override IInterceptor CreateInterceptor(IProxyRequest request)
return request.Context.Kernel.Get<CachingInterceptor>();
public class CachingInterceptor : IInterceptor
private ICache Cache get; set;
public CachingInterceptor(ICache cache)
Cache = cache;
public void Intercept(IInvocation invocation)
string className = invocation.Request.Target.GetType().FullName;
string methodName = invocation.Request.Method.Name;
object arguments = invocation.Request.Arguments;
StringBuilder builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
arguments.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
object retrieve = Cache.Retrieve<object>(cacheKey);
if (retrieve == null)
invocation.Proceed();
retrieve = invocation.ReturnValue;
Cache.Store(cacheKey, retrieve);
else
invocation.ReturnValue = retrieve;
Then you could decorate functions like this:
[Cache]
public virtual Customer GetCustomerByID(int customerID)
return CustomerRepository.GetCustomerByID(customerID);
Intercepted functions have to be virtual and classes must be created by the Ninject kernel. If you rely on performance, you could proxy classes directly via Castle.DynamicProxy (which is internally used by Ninject.Extensions.Interception.DynamicProxy).
Possibility 3: Use an Expression wrapper
You could pass the function as expression, generate a caching key containing class, method and parameter information and invoke the expression if not found in your Cache. This adds more runtime overhead than AOP / Proxy frameworks, but will be sufficient for simple solutions.
private T CacheAction<T>(Expression<Func<T>> action, [CallerMemberName] string memberName = "") where T : class
MethodCallExpression body = (MethodCallExpression)action.Body;
ICollection<object> parameters = new List<object>();
foreach (MemberExpression expression in body.Arguments)
parameters.Add(((FieldInfo)expression.Member).GetValue(((ConstantExpression)expression.Expression).Value));
StringBuilder builder = new StringBuilder(100);
builder.Append(GetType().FullName);
builder.Append(".");
builder.Append(memberName);
parameters.ToList().ForEach(x =>
builder.Append("_");
builder.Append(x);
);
string cacheKey = builder.ToString();
T retrieve = Cache.Retrieve<T>(cacheKey);
if (retrieve == null)
retrieve = action.Compile().Invoke();
Cache.Store(cacheKey, retrieve);
return retrieve;
public Customer GetCustomerByID(int customerID)
return CacheAction(() => CustomerRepository.GetCustomerByID(customerID));
edited May 3 '13 at 8:42
answered Apr 23 '13 at 5:50
DreselDresel
1,8482038
1,8482038
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
add a comment |
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
I like the third option, this way I can control whenever the method must be cached or not (passing a boolean attribute)
– William Borgo
Sep 11 '18 at 12:24
add a comment |
If I read you question correct, the right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it.
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
add a comment |
If I read you question correct, the right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it.
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
add a comment |
If I read you question correct, the right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it.
If I read you question correct, the right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it.
answered May 2 '12 at 11:27
mislmisl
793
793
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
add a comment |
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
1
1
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
code.google.com/p/mbcache
– Roger
Jun 29 '12 at 15:41
add a comment |
The Cache Application block is Microsoft's answer to built in library for Caching in .NET.
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
add a comment |
The Cache Application block is Microsoft's answer to built in library for Caching in .NET.
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
add a comment |
The Cache Application block is Microsoft's answer to built in library for Caching in .NET.
The Cache Application block is Microsoft's answer to built in library for Caching in .NET.
answered Feb 8 '11 at 4:31
George Stocker♦George Stocker
46.1k28155220
46.1k28155220
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
add a comment |
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
Note that as of Enterprise Library 6, the block was retired (see msdn.microsoft.com/en-us/library/dn169621.aspx). That's understandable as the functionality can be found in System.Runtime.Caching since .NET 4.0 (see msdn.microsoft.com/en-us/library/…).
– Philippe
Jan 29 '14 at 19:22
add a comment |
Lazy store it's value after first run.
Example: http://msdn.microsoft.com/en-us/vstudio/bb870976
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
add a comment |
Lazy store it's value after first run.
Example: http://msdn.microsoft.com/en-us/vstudio/bb870976
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
add a comment |
Lazy store it's value after first run.
Example: http://msdn.microsoft.com/en-us/vstudio/bb870976
Lazy store it's value after first run.
Example: http://msdn.microsoft.com/en-us/vstudio/bb870976
answered Nov 30 '11 at 15:36
ikutsinikutsin
8421122
8421122
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
add a comment |
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
in .NET 4 ++ ...
– CAD bloke
Jul 4 '14 at 21:25
add a comment |
I suggest Spring.Net AOP.
It basically creates a proxy and the calls can be redirected from/to the cache.
http://www.springframework.net/doc/reference/html/aop-quickstart.html
and then you can have something like that for your advice:
public class CachingAroundAdvice : IMethodInterceptor
{
#region Variable Declarations
private Priority priority = Priority.Normal;
#endregion
public object Invoke(IMethodInvocation invocation)
// declare local variables
string cacheKey = string.Empty;
object dataObject = null;
// build cache key with some algorithm
cacheKey = CreateCacheKey(invocation.Method, invocation.Arguments);
// retrieve item from cache
dataObject = CacheManager.Cache.GetData(cacheKey);
// if the dataobject is not in cache proceed to retrieve it
if (null == dataObject)
dataObject = invocation.Proceed();
// add item to cache
CacheManager.Cache.Add(cacheKey, dataObject, CachePriority, null, Expiration);
// return data object
return dataObject;
add a comment |
I suggest Spring.Net AOP.
It basically creates a proxy and the calls can be redirected from/to the cache.
http://www.springframework.net/doc/reference/html/aop-quickstart.html
and then you can have something like that for your advice:
public class CachingAroundAdvice : IMethodInterceptor
{
#region Variable Declarations
private Priority priority = Priority.Normal;
#endregion
public object Invoke(IMethodInvocation invocation)
// declare local variables
string cacheKey = string.Empty;
object dataObject = null;
// build cache key with some algorithm
cacheKey = CreateCacheKey(invocation.Method, invocation.Arguments);
// retrieve item from cache
dataObject = CacheManager.Cache.GetData(cacheKey);
// if the dataobject is not in cache proceed to retrieve it
if (null == dataObject)
dataObject = invocation.Proceed();
// add item to cache
CacheManager.Cache.Add(cacheKey, dataObject, CachePriority, null, Expiration);
// return data object
return dataObject;
add a comment |
I suggest Spring.Net AOP.
It basically creates a proxy and the calls can be redirected from/to the cache.
http://www.springframework.net/doc/reference/html/aop-quickstart.html
and then you can have something like that for your advice:
public class CachingAroundAdvice : IMethodInterceptor
{
#region Variable Declarations
private Priority priority = Priority.Normal;
#endregion
public object Invoke(IMethodInvocation invocation)
// declare local variables
string cacheKey = string.Empty;
object dataObject = null;
// build cache key with some algorithm
cacheKey = CreateCacheKey(invocation.Method, invocation.Arguments);
// retrieve item from cache
dataObject = CacheManager.Cache.GetData(cacheKey);
// if the dataobject is not in cache proceed to retrieve it
if (null == dataObject)
dataObject = invocation.Proceed();
// add item to cache
CacheManager.Cache.Add(cacheKey, dataObject, CachePriority, null, Expiration);
// return data object
return dataObject;
I suggest Spring.Net AOP.
It basically creates a proxy and the calls can be redirected from/to the cache.
http://www.springframework.net/doc/reference/html/aop-quickstart.html
and then you can have something like that for your advice:
public class CachingAroundAdvice : IMethodInterceptor
{
#region Variable Declarations
private Priority priority = Priority.Normal;
#endregion
public object Invoke(IMethodInvocation invocation)
// declare local variables
string cacheKey = string.Empty;
object dataObject = null;
// build cache key with some algorithm
cacheKey = CreateCacheKey(invocation.Method, invocation.Arguments);
// retrieve item from cache
dataObject = CacheManager.Cache.GetData(cacheKey);
// if the dataobject is not in cache proceed to retrieve it
if (null == dataObject)
dataObject = invocation.Proceed();
// add item to cache
CacheManager.Cache.Add(cacheKey, dataObject, CachePriority, null, Expiration);
// return data object
return dataObject;
answered Feb 8 '11 at 4:45
BurcephalBurcephal
39539
39539
add a comment |
add a comment |
I use this simple implementation of the System.Runetime.Caching namespace:
public class InMemoryCache : ICacheService
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(4));
return item;
public void Clear(string cacheKey)
MemoryCache.Default.Remove(cacheKey);
interface ICacheService
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
void Clear(string cacheKey);
Can be used in the following manner:
var cacheProvider = new InMemoryCache();
var cachedResult = cacheProvider.GetOrSet("YourCacheKey",
() => MethodToCache());
First call to the method will cache the result, the next call will return the cached result.
add a comment |
I use this simple implementation of the System.Runetime.Caching namespace:
public class InMemoryCache : ICacheService
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(4));
return item;
public void Clear(string cacheKey)
MemoryCache.Default.Remove(cacheKey);
interface ICacheService
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
void Clear(string cacheKey);
Can be used in the following manner:
var cacheProvider = new InMemoryCache();
var cachedResult = cacheProvider.GetOrSet("YourCacheKey",
() => MethodToCache());
First call to the method will cache the result, the next call will return the cached result.
add a comment |
I use this simple implementation of the System.Runetime.Caching namespace:
public class InMemoryCache : ICacheService
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(4));
return item;
public void Clear(string cacheKey)
MemoryCache.Default.Remove(cacheKey);
interface ICacheService
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
void Clear(string cacheKey);
Can be used in the following manner:
var cacheProvider = new InMemoryCache();
var cachedResult = cacheProvider.GetOrSet("YourCacheKey",
() => MethodToCache());
First call to the method will cache the result, the next call will return the cached result.
I use this simple implementation of the System.Runetime.Caching namespace:
public class InMemoryCache : ICacheService
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(4));
return item;
public void Clear(string cacheKey)
MemoryCache.Default.Remove(cacheKey);
interface ICacheService
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
void Clear(string cacheKey);
Can be used in the following manner:
var cacheProvider = new InMemoryCache();
var cachedResult = cacheProvider.GetOrSet("YourCacheKey",
() => MethodToCache());
First call to the method will cache the result, the next call will return the cached result.
answered Nov 16 '18 at 13:46
MichaelCleverlyMichaelCleverly
1,0531323
1,0531323
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4929540%2fis-there-anyway-to-cache-function-method-in-c-sharp%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
"I got bored with writing same to code again and again to cache the objects in data access layer. " - Inheritance perhaps?
– Mitch Wheat
Feb 8 '11 at 4:30
not Inheritance, don't want to write redundant code to check whether cache object exist or not? and then either make a call to actual object or take from cache. Any way "Yuriy Faktorovich" addressed every nicely. That is what i'm looking for exactly
– Veeru
Feb 8 '11 at 6:17