Udostępnij za pośrednictwem


Caching in Winforms / SmartClient Apps

Caching frequently-accessed data is often desirable in Winforms/Smart Client applications in order to maximise performance because reading a value from a well-designed cache can be less expensive, and/or provide fault tolerance (permitting limited off-line usage over unreliable networks, for example.) So what is the best way of doing this?

You have two options that I would recommend:

1. Use the built-in caching of the .NET framework (System.Web.Caching.Cache object) . Just because it’s in System.Web doesn’t mean it can’t be used for Winforms applications! This is the best choice if you do not need the cached data to be persisted to a physical backing store (i.e. written to anything other than memory). Guidance on using this class can be found here, and you can get a reference to it by creating a Factory class like this to return a static instance:

using System.Web.Caching;

using System.Web;

public sealed class MyCacheProvider
{
private MyCacheProvider(){};

public static Instance
{
get
{
return HttpRuntime.Cache;
}
}
}

2. Use the Caching Application Block . This provides more flexibility over the choice of backing store and comes with options to use memory, an optionally-encrypted file, or a database as your cache. Not using memory saves precious resources; plus using a file allows the cache to survive application restarts, and the database option allows several clients to leverage the same cached data. An example of how to use it follows:

using System.Windows.Forms;

using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace CachingExample

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            CacheManager manager = CacheFactory.GetCacheManager();

            manager.Add("MyKey", "This is the value I am caching.");

        }

    }

}

Comments

  • Anonymous
    October 21, 2007
    This article is a help. I was looking for caching in winform. Thanks :-)