Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using PostSharp to cache methods

0.00/5 (No votes)
9 May 2014 1  

Introduction

Using PostSharp's assembly modifications you can quite easily cut method consumption time down by caching methods. The library will find a marked cached method, and every call will be checked for with similar arguments, if the same arguments were found, it will immediately return the cached return value of the function call earlier.

Background

This trick uses a library called PostSharp, which has modifies your assembly. This allows you to track method calls and much more. Caching is not an old trick and has been around for a long time. Most web browsers use web page caching, and in this article I will show you how to cache methods within your assembly. Caching methods is a very interesting concept. To use this trick you must know what "caching your method" really means. Caching your method stores your method's return value after a call. Once the cached method is called once the arguments, return value, and method go into a dictionary.

Setting up your project

Before you start modifying your project you need to have included the article's source package. Make sure that you have also installed PostSharp via NuGet or by download. After installation, you also need to add PostSharp as a reference to your project.

After clicking "Add Reference...", A dialog should then appear. Make sure you click Browse -> Browse...

Then find PostSharp and click "OK", If you have done everything successfully, PostSharp should now be listed in your references.

Repeat this process instead by adding the CacheLibrary to your project's references.

Using the code

This library will work the best for methods that produce constant results, given the same arguments. This means that your method(s) should not use variables that involve time or randomness. To mark a method simply add the attribute StoreInCache to your method.

[StoreInCache]
public static int Foo(int bar)
{
    return bar;
}

History

5/8/14 - Updated CacheLibrary with new functionalities.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here