How to break through file-dependent caching in asp.net development--practical skills

Source: Internet
Author: User
You can use Session,application to cache data in a Web project, or you can cache it by using cache.

Today we are particularly concerned with cache caching. The cache is located under the namespace System.Web.Caching namespace, and what we see here is that it is used in WEB projects.

Description: The Cache class cannot be used outside of the asp.net application. It is designed and tested for use in asp.net to provide caching for WEB applications. In other types of applications, such as console applications or Windows forms applications, the ASP.net cache may not work correctly.

Here's a look at some cache caching dependencies:

Add an example of an item to the cache by specifying a dependency:
Copy Code code as follows:

Cache.Insert ("CacheItem2", "Cached Item 2");
string[] dependencies = {"CacheItem2"};
Cache.Insert ("CacheItem3", "Cached Item 3",
New System.Web.Caching.CacheDependency (null, dependencies));

Let's take a look at the use of a simple file-dependent cache, and everyone knows that cache supports file-dependent caching:
Cache.Insert ("CacheItem4", "Cached Item 4", New System.Web.Caching.CacheDependency (Server.MapPath ("XMLFile.xml"));
The following are multiple-dependent caching effects:
Copy Code code as follows:

System.Web.Caching.CacheDependency dep1 = new System.Web.Caching.CacheDependency (Server.MapPath ("XMLFile.xml"));
String[] KeyDependencies2 = {"CacheItem1"};
System.Web.Caching.CacheDependency DEP2 = new System.Web.Caching.CacheDependency (null, keyDependencies2);
System.Web.Caching.AggregateCacheDependency AGGDEP = new System.Web.Caching.AggregateCacheDependency ();
Aggdep.add (DEP1);
Aggdep.add (DEP2);
Cache.Insert ("CacheItem5", "Cached Item 5", AGGDEP);

The above code, the basic knowledge of cache some of the use of caching, but also to achieve the results we originally wanted. The following is a complete example to see the cache file relies on the use of caching.
First, you define an XML file whose contents are as follows and are accompanied by an entity class:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<Students>
<Student>
<Name>hechen</Name>
<Sex> male </Sex>
<Age>23</Age>
</Student>
<Student>
<Name> Love </Name>
<Sex> male </Sex>
<Age>23</Age>
</Student>
</Students>

Defines a class that reads the XML file above:
Copy Code code as follows:

public class Accessprovider
{
Public Accessprovider ()
{
}
Public list<student> getstudentlist (string filePath)
{
XElement root = Xelement.load (FilePath);
Ienumerable<xelement> enumerable = from E in root. Elements ("Student") select E;
list<student> list = new list<student> ();
Student Student = null;
foreach (xelement element in enumerable)
{
Student = new Student ();
Student. Name = element. Element ("Name"). Value;
Student. Age = Convert.ToInt32 (element. Element ("Age"). Value);
Student. Sex = element. Element ("Sex"). Value;
List. ADD (student);
}
return list;
}
}

Read cache and set file cache dependencies:
Copy Code code as follows:

public partial class Default:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
list<student> list = cache["Items1"] as list<student>;
if (list!= null && list. COUNT>0)
{
List. ForEach (item => {Response.Write) (item. Name + "" + Item. Age + "" +item. sex+ "<br/>"); });
}
Else
{
Accessprovider Provider = new Accessprovider ();
String fielpath = Server.MapPath ("~/xml/student.xml");
List = provider. Getstudentlist (Fielpath);
Cache.Insert ("Items1", List, new System.Web.Caching.CacheDependency (Fielpath));
}
}
}

Later will upload this example, after running the page, you can manually modify the above defined XML file, and then refresh the page to see the effect. Once you have modified the file, the cached content is invalidated and the contents of the XML file are again cached. The code here does not do too much explaining.
Cache can only be used as a web-gathering, so how can we solve this problem if we encounter a console project and other projects such as WinForm, without a dependency cache? Let's look at how to implement a file-dependent cache.
Goal: Implement when a file under a specific folder is modified, deleted, or added to invalidate the cache in the system or reload the cache.
Program Type: WinForm Program Web program Console Program
We use the simplest console program as an example, which is the most versatile.
First, here's a custom cache object:
Copy Code code as follows:

Namespace Cacheconsole
{
public class Cache
{
private static int num=50;
private static Object obj = new Object ();
Static Cache ()
{
}
public static int Get ()
{
return Num;
}
public static void Update (int argvalue)
{
Lock (obj)
{
Num = Argvalue;
}
}
}
}

The above cache is actually a static modified global variable, which defines a method of caching data acquisition and a method of caching updates, the static variable num as a cache container, the default initial value is 50. This cache container is a little bit simpler, but it can meet our requirements.
Assuming that our program relies on files located below the F:\File\ directory, we are going to monitor these files and implement the monitoring update cache code as follows:
Copy Code code as follows:

private static void Run ()
{
FileSystemWatcher watcher = new FileSystemWatcher ();
Watcher. Path = @ "F:\File\";
Watcher. NotifyFilter = Notifyfilters.creationtime | Notifyfilters.directoryname | Notifyfilters.filename | notifyfilters.lastaccess | notifyfilters.lastaccess | Notifyfilters.size;
Watcher. Filter = "*.txt";
Watcher. Created + = Delegate (object source, FileSystemEventArgs e) {Console.WriteLine ("Create New file:" + DateTime.Now.ToString ()); Cache.update (10); };
Watcher. Changed + = Delegate (object source, FileSystemEventArgs e) {Console.WriteLine ("File Modification:" + DateTime.Now.ToString ()); Cache.update (20); };
Watcher. Deleted + = Delegate (object source, FileSystemEventArgs e) {Console.WriteLine ("File deletion:" + DateTime.Now.ToString ()); Cache.update (30); };
Watcher. Renamed + = Delegate (object source, RenamedEventArgs e) {Console.WriteLine ("File Rename:" + DateTime.Now.ToString ()); Cache.update (40); };
Watcher. EnableRaisingEvents = true;
}

This program listens for file creation, modification, deletion, and renaming in a specific directory. Note that the program filters only. txt files.
Then we use a program to not only read the cached data
Copy Code code as follows:

static void Main (string[] args)
{
Run ();
for (int i = 1; I <= 10000; i++)
{
int value = Cache.get ();
Console.WriteLine ("First" +i+ "secondary Value:" +value);
Thread.Sleep (3000);
}
}

Start listening to the file, and then not only read the cached data. The operation effect is as follows:

Run the effect without making any changes to the file:

The file is created to run the following chart:

The effect of renaming a file is as follows:

The changes to the contents of the file run as follows:

The file system delete operation effect is as follows:

From the above figure can be seen, every time the file directory of TXT file modification will result in the cache data updates, this also reached our original goal. These cached data depend on these file systems.

Here everyone may think this is nonsense, wrote so much, in fact, the content is very simple, as a little knowledge to share. You can look at the use of FileSystemWatcher classes.

Sample code Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.