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)
EndSub
EndModule
Enjoy!