System.Runtime.Caching 命名空間是 .NET Framework 4 中的新命名空間。 此命名空間使緩存可供所有 .NET Framework 應用程序使用。
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 WPFCaching { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_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(10.0); List<string> filePaths = new List<string>(); filePaths.Add("c:\\cache\\cacheText.txt"); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); // Fetch the file contents. fileContents = File.ReadAllText("c:\\cache\\cacheText.txt") + "\n" + DateTime.Now.ToString(); cache.Set("filecontents", fileContents, policy); } MessageBox.Show(fileContents); } } }
如果未提供任何逐出或過期信息,則默認值為 InfiniteAbsoluteExpiration,這意味着緩存條目永遠不會僅基於絕對時間過期。 相反,緩存項僅在存在內存壓力時過期。 最佳做法是,應始終顯式提供絕對或可調過期。
HostFileChangeMonitor 對象監視文本文件的路徑,並在發生更改時通知緩存。 在此示例中,如果文件的內容發生更改,緩存項將過期。