在ASP.NET中使用Session与Application 对象

80酷酷网    80kuku.com

  application|asp.net|session|对象Last month (November 2001) I concluded that in ASP.NET, caching is the key to performance if you want to exploit Web controls and maintain optimal server response times. Caching relates directly to applications that can work disconnected from the data source. Not all applications can afford this. Applications that work in a highly concurrent environment that need to detect incoming changes to data can't be adapted to work disconnected. However, there are scenarios where you have a large block of user-specific data that needs to be analyzed, sorted, aggregated, scrolled, and filtered. In this case, your users need to extrapolate numbers and trends, but aren't interested in the last-minute record. In this case, server-side caching can be a key advantage.
Data caching can mean two things. You can temporarily park your frequently used data into memory data containers, or you can persist them to disk on the Web server or a machine downstream. But what is the ideal format for this data? And what is the most efficient way to load it back into an in-memory binary usable format? These are the questions I will answer this month.

ADO.NET and XML
ADO.NET and XML are the core technologies that help you design an effective caching subsystem. ADO.NET provides a namespace of data-oriented classes through which you can build a rough but functional in-memory DBMS. XML is the input and output language of this subsystem, but it's much more than the language used to serialize and deserialize living instances of ADO.NET objects. If you have XML documents formatted like data—hierarchical documents with equally sized subtrees—you can synchronize them to ADO.NET objects and use both XML-related technologies and relational approaches to walk through the collection of data rows. Although ADO.NET and XML are tightly integrated, only one ADO.NET object has the ability to publicly manipulate XML for reading and writing. This object is called the DataSet.
ASP.NET apps often end up handling DataSet objects. DataSet objects are returned by data adapter classes, which are one of the two ADO.NET command classes that get in touch with remote data sources. DataSets can also be created from local data—any valid stream object can be read into and populate a DataSet object.
The DataSet has a powerful, feature-rich programming interface and works as an in-memory cache of disconnected data. It is structured as a collection of tables and relationships. This makes it suitable when you have to work with related tables of data. Using DataSets, all of your tables are stored in a single container. This container knows how to serialize its content to XML and how to restore it to its original state. What more could you ask for from a data container?

Devising an XML-based Caching System
The majority of ASP.NET applications could take advantage of the Cache object for all of their caching needs. The Cache object is new to ASP.NET and provides unique and powerful features. It is a global, thread-safe object that does not store information on a per-session basis. In addition, the Cache is designed to ensure it does not tax the server's memory whatsoever. If memory pressure does become an issue, the Cache will automatically purge less recently used items based on a priority defined by the developer.
Like Application, though, the Cache object does not share its state across the machines of a Web farm. I'll have more to say about the Cache object later. Aside from Web farms, there are a few tough scenarios you might want to consider as alternatives to Cache. Even when you have large DataSets to store on a per-session basis, storing and reloading them from memory will be faster than any other approach. However, with many users connected at the same time, each storing large blocks of data, you might want to consider helping the Cache object to do its job better. An app-specific layered caching system built around the Cache object is an option. In this case, sensitive data will go into the Cache efficiently managed by ASP.NET. The rest of them could be cached in a slower but memory-free storage—for example, session-specific XML files. Let's look at writing and reading DataSets from disk.
Saving intermediate data to disk is a caching alternative that significantly reduces the demands on the Web server. To be effective, though, it should involve minimum overhead—just the time necessary to serialize and deserialize data. Custom schemas and proprietary data formats are unfit for this technique because the extra steps required introduce a delay. In .NET, you can use the DataSet object to fetch data and to persist it to disk. The DataSet object natively provides methods to save to XML and to load from it. These procedures, along with the internal representation of the DataSet, have been carefully optimized. They let you save and restore XML files in an amount of time that grows linearly (rather than geometrically) with the size of the data to process. So instead of storing persistent data sets to Session, you can save them on the server on a per-user basis with temporary XML files.
To recognize the XML file of a certain session, use the Session ID—an ASCII sequence of letters and digits that uniquely identifies a connected user. To avoid the proliferation of such files, you kill them when the session ends. Saving DataSet objects to XML does not affect the structure of the app, as it will continue to work with the DataSet object in mind. The writing and reading is performed by a couple of ad hoc methods provided by the DataSet object with a little help from .NET stream objects.

A Layered Caching System
If you want to use a cache mechanism to store data across multiple requests of the same page, your code will probably look like Figure 1. When the page first loads, you fetch all the data needed using the private member DataFromSourceToMemory. This function reads the rows from the data source and stores them into the cache, whatever it is. Then requests for the page will result in a call to DeserializeDataSource to fetch data. This call will try to load the DataSet from the cache and will resort to other physical access to the underlying DBMS if an exception is thrown. This can happen if the file is deleted from its location for any reason. Figure 2 shows the app's global.asax file. In the OnEnd event, the code deletes the XML file whose name matches the current session ID.
The global.asax file resides in the root directory of an ASP.NET application. When you run an ASP.NET application, you must use a virtual directory. If you test an ASP.NET page outside a virtual directory, you won't capture any session or application event in your global.asax file. Also, while Session_OnStart is always raised, the Session_OnEnd event is not guaranteed to fire in an out-of-process scenario.
Each active ASP.NET session is tracked using a 120-bit string that is composed of URL-legal ASCII characters. Session ID values are generated so uniqueness and randomness are guaranteed. This avoids collisions and makes it harder to guess the session ID of an existing session.
The following code shows how to use session ID to persist to and reload data from disk, serializing a DataSet to an XML file.

void SerializeDataSource(DataSet ds)
{
    String strFile;
    strFile = Server.MapPath(Session.SessionID + ".xml");
    XmlTextWriter xtw = new XmlTextWriter(strFile, null);
    ds.WriteXml(xtw);
    xtw.Close();
}

That code is equivalent to storing the DataSet in a Session slot.

Session["MyDataSet"] = ds;

Of course, the functionality of the previous two approaches is actually radically different.
To read back previously saved data, you can use this code:

DataSet DeserializeDataSource()
{
    String strFile;
strFile = Server.MapPath(Session.SessionID + ".xml");

// Read the content of the file into a DataSet
    XmlTextReader xtr = new XmlTextReader(strFile);
    DataSet ds = new DataSet();
    ds.ReadXml(xtr);
    xtr.Close();

    return ds;
}

This function locates an XML file whose name matches the ID of the current session and loads it into a newly created DataSet object. If you have a caching system based on the Session object, you should use this routine to replace any code that looks like this:

DataSet ds = (DataSet) Session["MyDataSet"];

How many of you remember the IBM 360/370s? When I was a first-year university student, I learned about memory management on them, which introduced virtual memory as a way to increase performance. It is structured like a pyramid of storage devices with decreasing size and increasing speed as you move from the bottom up.
Why all this history? Because an app-specific layered caching system built around the Cache object, even in the toughest scenario with the most stringent scalability requirements, can help the Cache object to perform in a better and more effective way.
Figure 3 shows some of the elements that could form the ASP.NET caching pyramid, but the design is not set in stone. The number and the type of layers are completely up to you, and are application-specific. In several Web applications, only one level is used: the DBMS tables level. If scalability is important, and your data is mostly disconnected, a layered caching system is almost a must.


(待续)

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: