Introduction

This articles describes the caching in WPF using the C# language. Caching is the way to store data in memory for rapid access, hence it provides both scalability and performance.

Caching Types

The types of caching are:

There are various classes provided by the .NET Framework located in the System.Runtime.caching namespace that enables the user to use caching in .NET Framework applications.

The advantages of implementing a data cache are:

Step 1

First we create a WPF application using the following procedure:

s.jpg

Step 2

To change the .NET framework use the following procedure:

Step 3

To add a reference to the caching Assemblies:

Step 4

s10.jpg
s7.jpg

Now the code for the MainWindow.xaml file:

<Window x:Class="caching.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="MainWindow" Height="350" Width="525">

<Grid>

<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="61,197,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />

</Grid>

</Window>

Step 5

Step 6

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.Runtime.Caching;

using System.IO;

namespace caching

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void button1_Click(object sender, RoutedEventArgs e)

{

ObjectCache c = MemoryCache.Default;

string fileContents = c["filecontents"] as string;

if (fileContents == null)

{

CacheItemPolicy p = new CacheItemPolicy();

p.AbsoluteExpiration =

DateTimeOffset.Now.AddSeconds(20.0);

List<string> filePaths = new List<string>();

filePaths.Add("c:\\cache\\cache file.txt");

p.ChangeMonitors.Add(new

HostFileChangeMonitor(filePaths));

// Fetch the file contents.

fileContents = File.ReadAllText("c:\\cache\\cache file.txt") + "\n" + DateTime.Now.ToString();

c.Set("filecontents", fileContents, p);

}

MessageBox.Show(fileContents);

}

}

}

Output

s2.jpg

Now click on the Button

s3.jpg


After 20 seconds when we again click on the button a new time is displayed that shows a cache entry has expired and a new cached content is displayed.

s4.jpg