Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Caching in C#

Status
Not open for further replies.

jaso77

Programmer
Jan 21, 2004
2
CA
when I compile the code below it compiles successfully. But when i run it it gives me the following error: Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.


What am i doing wrong?

using System.IO;
using System;
using System.Web;
using System.Web.Services;
using System.Web.Caching;
using System.Collections;
using System.Data;


public class weather
{

public static void Main(string[] args)
{
weather wh=new weather();
wh.display();
}


public void display()
{


Cache cache=new Cache();
Console.WriteLine ("compiled ok");

string Source;


// try to retrieve item from cache
// if it's not there, add it

Source =(String) cache["mykey"];


if (Source == null) {


String rawHtml="This is the string i want to cache";

Source = rawHtml;
cache["mykey"] = Source;

Console.WriteLine( "created explicitly");
}
else {
Console.WriteLine( "retrieved from cache");
}



}


}


 
First of all you should use try-catch block.
Looking at using namespaces , your references are to System.Web.Caching and the Cache class implements the cache for a Web application , or you are running your code as a console application.
-obislavu-
 
Yes I am running my application as a console application. Does that mean that the Cache class can only be used in web applications?
 
Yup.

If you want to cache something, you'll have to write your own, I'm afraid. But it's actually not that hard -- if you define a class to hold the items you want cached, you can store it in a Hashtable collection (which is sortof what the cache object does anyway). You assign a key to the cached item (from the cacheitem class you wrote), and add it to the Hashtable. When you need it later, you supply the key again and get it from the Hashtable (or not, if it's not been cached).

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top