在 WPF 应用程序中缓存应用程序数据
-
创建缓存类的实例,即,将实例化新的 MemoryCache 对象。
-
指定缓存使用 HostFileChangeMonitor 对象来监视文本文件中的更改。
-
读取文本文件并将其内容缓存为缓存条目。
-
显示缓存的文本文件的内容
创建WPFDemo 程序WpfApp2如下,验证使用 MemoryCache 缓存数据及缓存过期情况。
<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Button Width="100" Height="60" Content="Cache" Click="Button_Click"></Button> <Button Content="Button" HorizontalAlignment="Left" Margin="117,145,0,0" VerticalAlignment="Top" Width="124" Height="74" Click="Button_Click_1"/> </Grid> </Window>
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Caching; using System.Threading; using System.Windows; namespace WpfApp2 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ObjectCache cache = MemoryCache.Default; string fileContents = cache["filecontents"] as string; if (fileContents == null) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1000.0); List<string> filePaths = new List<string>(); filePaths.Add(@"C:\Users\wr\Desktop\cacheText.txt"); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); // Fetch the file contents. fileContents = File.ReadAllText(@"C:\Users\wr\Desktop\cacheText.txt") + "\n" + DateTime.Now.ToString(); cache.Set("filecontents", fileContents, policy); } MessageBox.Show(fileContents); } private void Button_Click_1(object sender, RoutedEventArgs e) { ObjectCache cache = MemoryCache.Default; string fileContents = cache["filecontents"] as string; cache.Set(cache.GetCacheItem("filecontents"), new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5.0) }); MessageBox.Show(cache["filecontents"].ToString()); Thread.Sleep(5000); MessageBox.Show(cache["filecontents"] == null ? "缓存已清空" :cache["filecontents"].ToString()); } } }