How to break through the file dependency cache in asp.net Development

Source: Internet
Author: User

In a Web project, you can use sessions, applications, and so on to Cache data or Cache data.

Today, we are particularly concerned with Cache. The Cache is located in the namespace System. Web. Caching. What we think of here is that it is used in Web projects.

Note: The Cache class cannot be used outside ASP. NET applications. It is designed and tested to provide caching for Web applications in ASP. NET. ASP. NET cache may not work properly in other types of applications (such as console applications or Windows Forms applications.

The following describes how to use Cache dependencies:

Example:
Copy codeThe Code is 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. We all know that Cache supports file dependent Cache:
Cache. Insert ("CacheItem4", "Cached Item 4", new System. Web. Caching. CacheDependency (Server. MapPath ("XMLFile. xml ")));
The following figure shows the multi-dependency cache effect:
Copy codeThe Code is 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 );

Through the above Code, we basically know some Cache-dependent usage, and also achieve the expected results. The following uses a complete example to check the usage of Cache files dependent on the Cache.
First, define an XML file with the following content and an object class:
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Students>
<Student>
<Name> hechen </Name>
<Sex> male </Sex>
<Age> 23 </Age>
</Student>
<Student>
<Name> sentiment </Name>
<Sex> male </Sex>
<Age> 23 </Age>
</Student>
</Students>

Define a class to read the above xml file:
Copy codeThe Code is 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 the cache and set the File Cache dependency:
Copy codeThe Code is 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 ));
}
}
}

This example will be uploaded later. After running the page, you can manually modify the xml file defined above, and then refresh the page to see the effect. After you modify this file, the cached content becomes invalid and you can read the xml file again. The code here is not explained too much.
Cache can only be used for Web gathering. What should we do if we encounter Console projects, WinForm and other projects, and do not have dependency Cache? How should we solve this problem. The following describes how to implement a file dependency cache.
Purpose: To modify, delete, or add files in a specific folder to invalidate the cache 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 universal.
First, define a cache object:
Copy codeThe Code is 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 global variable modified with Static, which defines a method for obtaining cache data and a cache update method. The Static variable Num is used as a cache container, the default value is 50. although this cache container is simple, it can meet our requirements.
Assume that the files on which our program depends are located in the F: \ File \ directory. Therefore, we need to monitor these files and implement the following code to monitor and update the cache:
Copy codeThe Code is as follows:
Private static void Run ()
{
FileSystemWatcher watcher = new FileSystemWatcher ();
Watcher. Path = @ "F: \ File \";
Watcher. policyfilter = policyfilters. CreationTime | policyfilters. DirectoryName | policyfilters. FileName | policyfilters. LastAccess | policyfilters. LastAccess | policyfilters. Size;
Watcher. Filter = "*. txt ";
Watcher. created + = delegate (object source, FileSystemEventArgs e) {Console. writeLine ("Create a 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 monitors file creation, modification, deletion, and rename in a specific directory. The program filters the listening .txt file.
Then we use a program to read not only the cached data
Copy codeThe Code is as follows:
Static void Main (string [] args)
{
Run ();
For (int I = 1; I <= 10000; I ++)
{
Int value = Cache. Get ();
Console. WriteLine ("no." + I + "value:" + value );
Thread. Sleep (3000 );
}
}

Start the file listening, and then not only need to read the cache data. The running effect is as follows:

Running effect without modifying the file:

 

Run the following command to create a file:

 

The effect of renaming a file is as follows:

 

The modification and running effect of the file content is as follows:

 

The following figure shows the effect of deleting a file system:

 

As shown in the figure above, every modification to the txt file in this file directory will result in cache data updates, which achieves our initial goal. The cached data depends on these file systems.

Everyone may think this is a nonsense here, so much is written. In fact, the content is very simple. Let's share it as a small knowledge point. For more information, see the use of the FileSystemWatcher class.

Download Sample Code

Related Article

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.