public GameTrackerService() { GamesDataUpdateTimer = new System.Timers.Timer(TimeSpan.FromDays(1).TotalMilliseconds) { AutoReset = true }; GamesDataUpdateTimer.Elapsed += (sender, args) => GameStore.ReloadGamesFromCentralRepository(); ProcessScannerTimer = new System.Timers.Timer(AppSettings.Instance.ProcessScanIntervalInSeconds * 1000) { AutoReset = true }; ProcessScannerTimer.Elapsed += (sender, args) => { new ProcessScanner().ScanProcesses(ProcessScannerTimer); }; UserActivityFileMonitor = new HostFileChangeMonitor(new[] { UserActivityStore.DataFilePath }.ToList()); UserActivityFileMonitor.NotifyOnChanged((_) => { AllUserActivityCache.CancellationTokenSource.Cancel(); }); WebAssetsFileMonitor = new HostFileChangeMonitor(WebAssets.AllAssetPaths.ToArray()); WebAssetsFileMonitor.NotifyOnChanged((_) => { WebAssets.CancellationTokenSource.Cancel(); }); WebHost = new WebHostBuilder() .UseKestrel() .UseStartup <WebHostConfiguration>() .UseConfiguration(AppSettings.Instance.Configuration) .UseSerilog() .UseUrls(WebHostListenAddress) .Build(); }
/// <summary> /// 添加到缓存 /// </summary> /// <param name="value">被缓存的数据</param> /// <param name="cacheKey">缓存key</param> /// <param name="filePath">依赖缓存文件的绝对路径</param> public static void SetCache_M(this object value, string cacheKey, string dependency_filePath) { if (!File.Exists(dependency_filePath)) { throw new FileNotFoundException("缓存依赖文件不存在"); } ObjectCache cache = MemoryCache.Default; CacheItemPolicy policy = new CacheItemPolicy(); //缓存优先级别 policy.Priority = System.Runtime.Caching.CacheItemPriority.Default; cache.Set(cacheKey, value, policy); //设置监视对象 HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>() { dependency_filePath }); //设置监视对象的回调操作 //依赖文件发生变化 即删除缓存 monitor.NotifyOnChanged(new OnChangedCallback(o => { RemoveCache_M(cacheKey); })); //添加到监视器 policy.ChangeMonitors.Add(monitor); }
/// <summary> /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存 /// </summary> /// <returns></returns> public static List <ReportTemplateFile> GetReportTemplates() { List <ReportTemplateFile> reportTemplates = null; ObjectCache cache = MemoryCache.Default; if (cache.Contains(CacheKey)) { reportTemplates = cache.GetCacheItem(CacheKey).Value as List <ReportTemplateFile>; } else { reportTemplates = LoadReportTemplates(); if (reportTemplates.Any()) { CacheItemPolicy policy = new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable }; cache.Set(CacheKey, reportTemplates, policy); var fileInfos = new DirectoryInfo(ReportTemplateFilesPath).GetFiles().ToList(); List <string> filePaths = fileInfos.Select(f => f.FullName).ToList(); HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths); monitor.NotifyOnChanged(new OnChangedCallback((o) => cache.Remove(CacheKey))); policy.ChangeMonitors.Add(monitor); } } return(reportTemplates); }
/// <summary> /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存 /// </summary> /// <returns></returns> public static List <ClientApplicationVersion> GetClientApplicationVersion() { List <ClientApplicationVersion> clientApplicationVersions = null; ObjectCache cache = MemoryCache.Default; if (cache.Contains(CacheKey)) { clientApplicationVersions = cache.GetCacheItem(CacheKey).Value as List <ClientApplicationVersion>; } else { clientApplicationVersions = LoadClientApplicationConfigs(); if (clientApplicationVersions.Any()) { CacheItemPolicy policy = new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable }; cache.Set(CacheKey, clientApplicationVersions, policy); List <string> filePaths = new List <string> { ClientAppVersionConfigFile }; HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths); monitor.NotifyOnChanged(new OnChangedCallback((o) => cache.Remove(CacheKey))); policy.ChangeMonitors.Add(monitor); } } return(clientApplicationVersions); }
public void Constructor_Duplicates() { HostFileChangeMonitor monitor; PlatformID pid = Environment.OSVersion.Platform; bool runningOnWindows = ((int)pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); string missingFile = Path.Combine("missing", "file", "path"); if (runningOnWindows) { missingFile = "c:\\file.txt"; } else { missingFile = "/file.txt"; } var paths = new List <string> { missingFile, missingFile }; // Just checks if it doesn't throw any exception for dupes monitor = new HostFileChangeMonitor(paths); monitor.Dispose(); }
public void Constructor_Exceptions() { HostFileChangeMonitor monitor; string relPath = Path.Combine("relative", "file", "path"); var paths = new List <string> { relPath }; Assert.Throws <ArgumentException> (() => { monitor = new HostFileChangeMonitor(paths); }, "#A1"); paths.Clear(); paths.Add(null); Assert.Throws <ArgumentException> (() => { monitor = new HostFileChangeMonitor(paths); }, "#A2"); paths.Clear(); paths.Add(String.Empty); Assert.Throws <ArgumentException> (() => { monitor = new HostFileChangeMonitor(paths); }, "#A3"); Assert.Throws <ArgumentNullException> (() => { monitor = new HostFileChangeMonitor(null); }, "#A4"); paths.Clear(); Assert.Throws <ArgumentException> (() => { monitor = new HostFileChangeMonitor(paths); }, "#A5"); }
static void Constructor_MissingFiles_Handler() { HostFileChangeMonitor monitor; PlatformID pid = Environment.OSVersion.Platform; bool runningOnWindows = ((int)pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); string missingFile = Path.Combine("missing", "file", "path"); if (runningOnWindows) { missingFile = "c:\\" + missingFile; } else { missingFile = "/" + missingFile; } var paths = new List <string> { missingFile }; // Actually thrown by FileSystemWatcher constructor - note that the exception message suggests the file's // parent directory is being watched, not the file itself: // // MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles: // System.ArgumentException : The directory name c:\missing\file is invalid. // at System.IO.FileSystemWatcher..ctor(String path, String filter) // at System.IO.FileSystemWatcher..ctor(String path) // at System.Runtime.Caching.FileChangeNotificationSystem.System.Runtime.Caching.Hosting.IFileChangeNotificationSystem.StartMonitoring(String filePath, OnChangedCallback onChangedCallback, Object& state, DateTimeOffset& lastWriteTime, Int64& fileSize) // at System.Runtime.Caching.HostFileChangeMonitor.InitDisposableMembers() // at System.Runtime.Caching.HostFileChangeMonitor..ctor(IList`1 filePaths) // at MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles() in c:\users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\HostFileChangeMonitorTest.cs:line 68 Assert.Throws <ArgumentException> (() => { monitor = new HostFileChangeMonitor(paths); }, "#A1"); if (runningOnWindows) { missingFile = "c:\\file.txt"; } else { missingFile = "/file.txt"; } paths.Clear(); paths.Add(missingFile); monitor = new HostFileChangeMonitor(paths); Assert.AreEqual(1, monitor.FilePaths.Count, "#A2-1"); Assert.AreEqual(missingFile, monitor.FilePaths [0], "#A2-2"); Assert.AreEqual(missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A2-4"); monitor.Dispose(); paths.Add(missingFile); monitor = new HostFileChangeMonitor(paths); Assert.AreEqual(2, monitor.FilePaths.Count, "#A3-1"); Assert.AreEqual(missingFile, monitor.FilePaths [0], "#A3-2"); Assert.AreEqual(missingFile, monitor.FilePaths [1], "#A3-3"); Assert.AreEqual(missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A3-4"); monitor.Dispose(); }
/// <summary> /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存 /// </summary> /// <param name="cacheKey">缓存Key</param> /// <param name="path">文件路径</param> /// <param name="func">获取xml内容</param> /// <returns>配置词典</returns> private static object GetConfigDictionary(string cacheKey, string path, Func <string, object> func) { object configs = new object(); ObjectCache cache = MemoryCache.Default; if (cache.Contains(cacheKey)) { var cacheItem = cache.GetCacheItem(cacheKey); if (cacheItem != null) { configs = cacheItem.Value; } } else { configs = func(path); CacheItemPolicy policy = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable }; cache.Set(cacheKey, configs, policy); List <string> filePaths = new List <string>() { path }; HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths); monitor.NotifyOnChanged((o) => { cache.Remove(cacheKey); }); policy.ChangeMonitors.Add(monitor); } return(configs); }
/// <summary> /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存 /// </summary> /// <param name="cacheKey">缓存Key</param> /// <returns>配置词典</returns> public static Dictionary <string, string> GetConfigDictionary(string cacheKey) { Dictionary <string, string> configs = null; //1、获取内存缓存对象 var cache = MemoryCache.Default; //2、通过Key判断缓存中是否已有词典内容(Key在存入缓存时设置) if (cache.Contains(cacheKey)) { //3、直接从缓存中读取词典内容 configs = cache.GetCacheItem(cacheKey).Value as Dictionary <string, string>; } else { //3、读取配置文件,组成词典对象,准备放到缓存中 configs = GetFromXml(); //4、检查是否读取到配置内容 if (configs != null) { //4、新建一个CacheItemPolicy对象,该对象用于声明配置对象在缓存中的处理策略 CacheItemPolicy policy = new CacheItemPolicy(); //5、因为配置文件一直需要读取,所以在此设置缓存优先级为不应删除 // 实际情况请酌情考虑,同时可以设置AbsoluteExpiration属性指定过期时间 policy.Priority = CacheItemPriority.NotRemovable; //6、将词典内容添加到缓存,传入 缓存Key、配置对象、对象策略 // Set方法首先会检查Key是否在缓存中存在,如果存在,更新value,不存在则创建新的 // 这里先加入缓存再加监视的原因是:在缓存加入时,也会触发监视事件,会导致出错。 cache.Set(cacheKey, configs, policy); //7、监视文件需要传入一个IList对象,所以即便只有一个文件也需要新建List对象 string applicationPath = AppDomain.CurrentDomain.BaseDirectory; string configPath = applicationPath + "MemeryCacheTest.exe.config"; List <string> filePaths = new List <string>() { @"c:\config.xml", configPath }; //8、新建一个文件监视器对象,添加对资源文件的监视 HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths); //9、调用监视器的NotifyOnChanged方法传入发生改变时的回调方法 monitor.NotifyOnChanged(new OnChangedCallback((o) => { cache.Remove(cacheKey); } )); //10、为配置对象的缓存策略加入监视器 policy.ChangeMonitors.Add(monitor); } } return(configs); }
public object AddOrGetExisting(string key, object value, string dependencyFile) { var policy = this.BuildDefaultPolicy(); var files = new List <string>(); files.Add(dependencyFile); var dependency = new HostFileChangeMonitor(files); return(this.Cache.AddOrGetExisting(key, value, policy)); }
private void buttonAddCache_Click(object sender, RoutedEventArgs e) { ObjectCache oCache = MemoryCache.Default; #region DosyaCache // Dosya bazlı bir bağımlılık politikası üretimi CacheItemPolicy policy = new CacheItemPolicy(); // Önce Policy tipi oluşturulur // Policy tipi için yeni bir dosya değişikliğini takip eden monitor nesnesi eklenir HostFileChangeMonitor cMonitor = new HostFileChangeMonitor(new List <string> { filePath }); // Monitor örneğin ilkelere eklenir policy.ChangeMonitors.Add(cMonitor); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(15); // Ön belleğe PDF tipinden olan dosya bir byte[] dizisi şeklinde eklenir. İkinci parametre de dependency belirtilir byte[] bytes = File.ReadAllBytes(filePath); mCache.Add("Aspnet40", bytes, policy); #endregion #region Class Cache // Custom Type türevli bir örneğin ön belleğe eklenmesi Person person1 = new Person(); person1.Name = "Mustafa"; person1.Surname = "TEKERASLAN"; person1.Salary = 1000; person1.BirthDate = new DateTime(1989, 1, 1); mCache.Add("Person", person1, DateTimeOffset.Now.AddSeconds(30)); // Eklenme anından itibaren 30 saniye süreyle ön bellekte tutulacağı DateTimeOffset yardımıyla belirtilir #endregion #region DB Cache // Ön belleğe DataTable türünden bir nesne örneğinin eklenmesi DataTable table = new DataTable(); using (SqlConnection conn = new SqlConnection("data source=(local);database=Northwnd;integrated security=SSPI")) { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataAdapter adapter = new SqlDataAdapter("Select * From Products", conn); adapter.Fill(table); } mCache.Add("Products", table, DateTimeOffset.Now.AddMinutes(1)); // DataTable içeriği eklenme anından itibaren iki dakika süreyle ön bellekte tutulacaktır #endregion MessageBox.Show("Cache'e Kaydedildi"); }
public T AddOrGetExisting <T>(string key, T value, string dependencyFile) { var policy = this.BuildDefaultPolicy(); var files = new List <string>(); files.Add(dependencyFile); var dependency = new HostFileChangeMonitor(files); var result = this.Cache.AddOrGetExisting(key, value, policy); return(result is T ? (T)result : default(T)); }
/// <summary> /// 添加缓存项 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dependency">缓存依赖文件</param> /// <returns></returns> public bool Add(string key, object value, string dependencyFile) { var policy = this.BuildDefaultPolicy(); var files = new List <string>(); files.Add(dependencyFile); var dependency = new HostFileChangeMonitor(files); policy.ChangeMonitors.Add(dependency); return(Cache.Add(key, value, policy)); }
public void Constructor_Duplicates() { HostFileChangeMonitor monitor; string missingFile = Path.GetFullPath(Guid.NewGuid().ToString("N")); var paths = new List <string> { missingFile, missingFile }; // Just checks if it doesn't throw any exception for dupes monitor = new HostFileChangeMonitor(paths); monitor.Dispose(); }
public XmlDocument Read() { var ds = new DataSet(); if (String.IsNullOrEmpty(_filePath)) { throw new ArgumentException("Invalid configFilePath."); } var key = _filePath; lock (this) { var data = objectCache[key] as XmlDocument; if (data != null) { Utility.DebugLog(String.Format("[From Cache] XmlCacheConfig ({0})", _filePath)); return(data); } if (!File.Exists(_filePath)) { throw new FileNotFoundException(String.Format("ConfigFile {0} not found.", _filePath)); } var policy = new CacheItemPolicy(); var monitor = new HostFileChangeMonitor(new List <string> { key }); policy.ChangeMonitors.Add(monitor); policy.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(720); var wrapperData = new XmlDocument(); var text = File.ReadAllText(_filePath); if (!String.IsNullOrEmpty(text)) { var bts = Encoding.UTF8.GetBytes(text); wrapperData.Load(new MemoryStream(bts)); } Utility.DebugLog(String.Format("[From Resource] XmlCacheConfig ({0})", _filePath)); objectCache.Set(key, wrapperData, policy); return(wrapperData); } }
static DsConfigurationManager() { HostFileChangeMonitor hfcm = new HostFileChangeMonitor(new List <string> { ConfigurationFileHelper.GetRootConfigurationFilePath() }); policy.ChangeMonitors.Add(hfcm); //FileSystemWatcher watcher = new FileSystemWatcher(); //watcher.Path = watchPath; //watcher.Filter = "*.config"; //watcher.NotifyFilter = NotifyFilters.Size; //watcher.Changed += new FileSystemEventHandler(watcher_Changed); //watcher.EnableRaisingEvents = true; }
static void Constructor_Calls_StartMonitoring_Handler() { Tuple <string, string, string, IList <string> > setup = null; try { var tns = new TestNotificationSystem(); ObjectCache.Host = tns; setup = SetupMonitoring(); var monitor = new HostFileChangeMonitor(setup.Item4); Assert.IsTrue(tns.StartMonitoringCalled, "#A1-1"); Assert.AreEqual(2, tns.StartMonitoringCallCount, "#A1-2"); } finally { CleanupMonitoring(setup); } }
public void Set(string key, object value, int minutes, params string[] monitorFiles) { var item = new CacheItem(key, value); var policy = new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromMinutes(minutes) }; if (monitorFiles != null && monitorFiles.Length > 0) { var monitor = new HostFileChangeMonitor(monitorFiles); policy.ChangeMonitors.Add(monitor); } Cache.Set(item, policy); }
/** * @ 创建目录类型的缓存,主要用于监控文件数量 * @ key 缓存的键 * @ path 路径,请确保路径存在 * @ offset 缓存有效时间 * @ searchPattern 搜索匹配关键字,默认:* * @ searchOption 文件搜索选项,默认TopDirectoryOnly * @ direcotryOption 目录缓存选项,默认FileAmountOnly * @ priority 逐出缓存优先级策略 * */ public static string CreateDirectoryCache(string key, string path, DateTimeOffset offset, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly, DirectoryOption direcotryOption = DirectoryOption.FileAmountOnly, CacheItemPriority priority = CacheItemPriority.Default) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key不能为空"); } if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path不能为空"); } bool isNotExists = Directory.Exists(path); if (isNotExists) { throw new ArgumentNullException(string.Format("指定目录:{0}不存在!", path)); } object values = GLCacheExpiration.Cache.Get(key); if (values == null) { CacheItemPolicy policy = new CacheItemPolicy(); List <string> fp = new List <string>() { path }; HostFileChangeMonitor monitor = new HostFileChangeMonitor(fp); policy.AbsoluteExpiration = offset; policy.Priority = priority; policy.ChangeMonitors.Add(monitor); string[] files = Directory.GetFiles(path, searchPattern, searchOption); if (direcotryOption == DirectoryOption.FileAmountOnly) { values = files == null ? 0 : files.Length; } else if (direcotryOption == DirectoryOption.FileNameArray) { values = files; } CacheItem chitem = new CacheItem(key, values); Cache.AddOrGetExisting(chitem, policy); } return(values.ToString()); }
public void UniqueId() { Tuple <string, string, string, IList <string> > setup = null; try { setup = SetupMonitoring(); FileInfo fi; var monitor = new HostFileChangeMonitor(setup.Item4); var sb = new StringBuilder(); fi = new FileInfo(setup.Item2); sb.AppendFormat("{0}{1:X}{2:X}", setup.Item2, fi.LastWriteTimeUtc.Ticks, fi.Length); fi = new FileInfo(setup.Item3); sb.AppendFormat("{0}{1:X}{2:X}", setup.Item3, fi.LastWriteTimeUtc.Ticks, fi.Length); Assert.Equal(sb.ToString(), monitor.UniqueId); var list = new List <string>(setup.Item4); list.Add(setup.Item1); monitor = new HostFileChangeMonitor(list); var di = new DirectoryInfo(setup.Item1); sb.AppendFormat("{0}{1:X}{2:X}", setup.Item1, di.LastWriteTimeUtc.Ticks, -1L); Assert.Equal(sb.ToString(), monitor.UniqueId); list.Add(setup.Item1); monitor = new HostFileChangeMonitor(list); Assert.Equal(sb.ToString(), monitor.UniqueId); monitor.Dispose(); } finally { CleanupMonitoring(setup); } }
private static void OnConfigFileChanged(object obj) { if (ServerConnectionSettings.s_Monitor != null && ServerConnectionSettings.s_Monitor.HasChanged) { if (ServerConnectionSettings.LoadConfigSettings(ServerConnectionSettings.s_DefaultConfigurationFile)) { try { EventHandler configFileChanged = ServerConnectionSettings.ConfigFileChanged; if (configFileChanged != null) { configFileChanged((object)null, EventArgs.Empty); } } catch (Exception ex) { string message = string.Format("Error notifying for file changes\r\n{0}", (object)ex.ToString()); Trace.TraceWarning(message); if (ServerConnectionSettings.s_EventLog != null) { ServerConnectionSettings.s_EventLog.WriteEntry(message, EventLogEntryType.Warning); } } } } ServerConnectionSettings.s_Monitor = (HostFileChangeMonitor)null; try { ServerConnectionSettings.s_Monitor = new HostFileChangeMonitor((IList <string>) new List <string>() { ServerConnectionSettings.s_DefaultConfigurationFile }); ServerConnectionSettings.s_Monitor.NotifyOnChanged(new OnChangedCallback(ServerConnectionSettings.OnConfigFileChanged)); } catch (Exception ex) { string message = string.Format("Error establishing change notifications\r\n{0}", (object)ex.ToString()); Trace.TraceWarning(message); if (ServerConnectionSettings.s_EventLog == null) { return; } ServerConnectionSettings.s_EventLog.WriteEntry(message, EventLogEntryType.Warning); } }
public static void Constructor_MissingFiles_Handler() { HostFileChangeMonitor monitor; string missingFile = Path.GetFullPath(Path.Combine(Guid.NewGuid().ToString("N"), "file", "path")); var paths = new List <string> { missingFile }; // Actually thrown by FileSystemWatcher constructor - note that the exception message suggests the file's // parent directory is being watched, not the file itself: // // MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles: // System.ArgumentException : The directory name c:\missing\file is invalid. // at System.IO.FileSystemWatcher..ctor(String path, String filter) // at System.IO.FileSystemWatcher..ctor(String path) // at System.Runtime.Caching.FileChangeNotificationSystem.System.Runtime.Caching.Hosting.IFileChangeNotificationSystem.StartMonitoring(String filePath, OnChangedCallback onChangedCallback, Object& state, DateTimeOffset& lastWriteTime, Int64& fileSize) // at System.Runtime.Caching.HostFileChangeMonitor.InitDisposableMembers() // at System.Runtime.Caching.HostFileChangeMonitor..ctor(IList`1 filePaths) // at MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles() in c:\users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\HostFileChangeMonitorTest.cs:line 68 Assert.Throws <ArgumentException>(() => { new HostFileChangeMonitor(paths); }); missingFile = Path.GetFullPath(Guid.NewGuid().ToString("N")); paths.Clear(); paths.Add(missingFile); monitor = new HostFileChangeMonitor(paths); Assert.Equal(1, monitor.FilePaths.Count); Assert.Equal(missingFile, monitor.FilePaths[0]); //?? Assert.Equal(missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId); monitor.Dispose(); paths.Add(missingFile); monitor = new HostFileChangeMonitor(paths); Assert.Equal(2, monitor.FilePaths.Count); Assert.Equal(missingFile, monitor.FilePaths[0]); Assert.Equal(missingFile, monitor.FilePaths[1]); //?? Assert.Equal(missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId); monitor.Dispose(); }
static void Dispose_NullState_NoStopMonitoring_Handler() { Tuple <string, string, string, IList <string> > setup = null; try { var tns = new TestNotificationSystem(); tns.UseNullState = true; ObjectCache.Host = tns; setup = SetupMonitoring(); var monitor = new HostFileChangeMonitor(setup.Item4); tns.FakeChanged(setup.Item2); Assert.IsFalse(tns.StopMonitoringCalled, "#A1-1"); Assert.AreEqual(0, tns.StopMonitoringCallCount, "#A1-2"); } finally { CleanupMonitoring(setup); } }
/// <summary> /// 监视配置文件 /// </summary> public static void MonitorConfigFile(EventHandler <SupportPlatformsChangedEventArgs> callbackOnConfigChangedHandler) { //使用基于文件缓存依赖的方式去监听文件 而不是使用 FileSystemWatch var cacheContainer = MemoryCache.Default; string cacheKey = "SupportPlatform-MonitorConfigFile"; if (cacheContainer.Contains(cacheKey)) { cacheContainer.Remove(cacheKey); } if (null != callbackOnConfigChangedHandler) { //如果已经存在这个缓存 表示已经加入了依赖监视 ,直接注册委托广播源即可 OnConfigFileChanged += callbackOnConfigChangedHandler; } //缓存策略 var policy = new CacheItemPolicy(); //绝对过期 policy.Priority = CacheItemPriority.NotRemovable; cacheContainer.Add(new CacheItem(cacheKey, DateTime.Now.ToString()), policy); //开启文件缓存 进行监视依赖 HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string> { configFilePath }); //当文件发生变更的时候 触发通知 monitor.NotifyOnChanged((state) => { //获取最新的配置 并触发事件 //var lstNewConfigs = SupportPlatformLoader.LoadConfig();CurrentSupportPlatforms = lstNewConfigs //直接 通知订阅的事件 将内容列表清空 ,再次重新加载即可 if (null != OnConfigFileChanged) { OnConfigFileChanged(null, new SupportPlatformsChangedEventArgs { }); } }); policy.ChangeMonitors.Add(monitor); }
private static void Dispose_Calls_StopMonitoring_Handler() { Tuple <string, string, string, IList <string> > setup = null; try { var tns = new TestNotificationSystem(); ObjectCache.Host = tns; setup = SetupMonitoring(); var monitor = new HostFileChangeMonitor(setup.Item4); tns.FakeChanged(setup.Item2); Assert.True(tns.StopMonitoringCalled); Assert.Equal(2U, tns.StopMonitoringCallCount); } finally { CleanupMonitoring(setup); } }
public bool Register<T>(string key,string filePath, Func<byte[],T> adapter) { ObjectCache configurationCache = MemoryCache.Default; CacheItemPolicy policy = new CacheItemPolicy(); HostFileChangeMonitor hfcm = new HostFileChangeMonitor(new List<string> { filePath }); policy.ChangeMonitors.Add(hfcm); if (configurationCache.Contains(key)) return false; if (File.Exists(filePath)) { using (FileStream sFile = new FileStream(filePath, FileMode.Open)) { byte[] data = new byte[sFile.Length]; sFile.Read(data, 0, data.Length); configurationCache.Set(key, adapter(data), policy); } return true; } else { throw new Exception("Register file does not exist!"); }; }
public void Add <T>(string key, string dependencyKey, T obj, TimeSpan timeSpan) { if (obj == null) { return; } var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + timeSpan }; LocalCache.Add(new CacheItem(key, obj), policy); HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>() { dependencyKey }); monitor.NotifyOnChanged(new OnChangedCallback((o) => { LocalCache.Remove(key); })); policy.ChangeMonitors.Add(monitor); }
public void Add <T>(string key, string dependencyKey, T obj) { if (obj == null) { return; } var policy = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable }; LocalCache.Add(new CacheItem(key, obj), policy); HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>() { dependencyKey }); monitor.NotifyOnChanged(new OnChangedCallback((o) => { LocalCache.Remove(key); })); policy.ChangeMonitors.Add(monitor); }
private bool RegisterMoniter(string key, params string[] dependentFiles) { if (this._isDisposed) { return(false); } string moniterKey = key + "|" + string.Join("|", dependentFiles); if (!this._monitors.ContainsKey(moniterKey)) { lock (this._monitors) { if (!this._monitors.ContainsKey(moniterKey)) { HostFileChangeMonitor moniter = new HostFileChangeMonitor(dependentFiles); moniter.NotifyOnChanged(delegate(object state) { try { this.Remove(key); moniter.Dispose(); } catch { } finally { this._monitors.Remove(moniterKey); this.RegisterMoniter(key, dependentFiles); } }); this._monitors.Add(moniterKey, moniter); } } } return(true); }
/** * @ 创建文件系统类型的缓存 * @ key 缓存的键 * @ filePath 文件路径 * @ offset 缓存有效时间 * @ priority 逐出缓存优先级策略 * */ public static string CreateFileCache(string key, string filePath, DateTimeOffset offset, CacheItemPriority priority = CacheItemPriority.Default) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key不能为空"); } if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath不能为空"); } bool isNotExists = File.Exists(filePath); if (isNotExists) { throw new ArgumentNullException(string.Format("指定文件:{0}不存在!", filePath)); } object values = GLCacheExpiration.Cache.Get(key); if (values == null) { CacheItemPolicy policy = new CacheItemPolicy(); List <string> fp = new List <string>() { filePath }; HostFileChangeMonitor monitor = new HostFileChangeMonitor(fp); policy.AbsoluteExpiration = offset; policy.Priority = priority; policy.ChangeMonitors.Add(monitor); values = File.ReadAllText(filePath); CacheItem chitem = new CacheItem(key, values); Cache.AddOrGetExisting(chitem, policy); } return(values.ToString()); }