Using the System.Web.Cache in a WinForms application

Some time ago I wrote an article about using the ASP.NET security providers in a WinForm application. Off course there are more usefull goodies in the System.Web namespaces to “borrow” like the Cache. In fact this is so easy that there is little point in writing an article about it. All you need to do is add a reference to System.Web and you are ready to use it.
Using it is real simple. Adding something to the Cache is done with “HttpRuntime.Cache.Insert(key, value)” or one of the overloads with dependencies or expiration values. Retrieving it is just as easy, just use: “HttpRuntime.Cache.Item(key)” and cast it to the right type.
Only one gotcha you might run into is trying to new up a Cache object and using it. In that case you will receive a System.NullReferenceException was unhandled exception with message “Object reference not set to an instance of an object.”. The solution is to use it through the HttpRuntime object instead of creating your own.
Imports System.Web
Module Module1
    Sub Main()
        Dim key AsString = “The Key”
        Dim value AsString = “The Value”
        Console.WriteLine(“The value = ‘{0}'”, value)
        HttpRuntime.Cache.Insert(key, value)
        value = “Something else”
        Console.WriteLine(“The value = ‘{0}'”, value)
        value = CType(HttpRuntime.Cache.Item(key), String)
        Console.WriteLine(“The value = ‘{0}'”, value)

5 thoughts on “Using the System.Web.Cache in a WinForms application

  1. Maurice, what’s the advantage of using this class? Why not use a dictionary instead? No casting needed..etc.

    Imports System.Collections.Generic

    Module Module1

    Sub Main()

    Dim key As String = “The Key”
    Dim value As String = “The Value”
    Console.WriteLine(“The value = ‘{0}'”, value)

    Dim dic As New Dictionary(Of String, String)
    dic.Add(key, value)

    value = “Something else”
    Console.WriteLine(“The value = ‘{0}'”, value)

    value = dic(key)
    Console.WriteLine(“The value = ‘{0}'”, value)

    End Sub
    End Module

  2. Using a dictionary is great if you just want to store some information and be done with it. A cache gives you a lot of additional functionality though. Using expiration, both fixed and sliding, you can automatically remove items that haven’t been used for a while. Or using dependecies you can automatically remove items when a certian condition is met, for example when a config file is changed or when the result of a SQL query changes.

  3. Hi,
    useful article. I had ‘new’ed up the Cache class in my app and when called from NUnit was getting this null object reference. Using HttpRuntime helped me fix it .


Leave a Reply

Your email address will not be published. Required fields are marked *