2 using System.Collections.Generic;
5 using System.Reflection;
8 using System.Threading;
10 namespace Irony.GrammarExplorer {
15 private TimeSpan _autoRefreshDelay = TimeSpan.FromMilliseconds(500);
16 private Dictionary<string, CachedAssembly> _cachedAssemblies =
new Dictionary<string, CachedAssembly>();
18 class CachedAssembly {
20 public DateTime LastWriteTime;
21 public FileSystemWatcher Watcher;
22 public Assembly Assembly;
30 if (SelectedGrammar == null)
33 var type = SelectedGrammarAssembly.GetType(SelectedGrammar.TypeName,
true,
true);
34 return Activator.CreateInstance(type) as
Parsing.Grammar;
37 Assembly SelectedGrammarAssembly {
39 if (SelectedGrammar == null)
43 var location = SelectedGrammar.Location;
44 if (!_cachedAssemblies.ContainsKey(location)) {
45 var fileInfo =
new FileInfo(location);
46 _cachedAssemblies[location] =
48 LastWriteTime = fileInfo.LastWriteTime,
49 FileSize = fileInfo.Length,
54 _cachedAssemblies[location].Watcher = CreateFileWatcher(location);
58 var assembly = _cachedAssemblies[location].Assembly;
59 if (assembly == null) {
60 assembly = LoadAssembly(location);
61 _cachedAssemblies[location].Assembly = assembly;
68 private FileSystemWatcher CreateFileWatcher(
string location) {
69 var folder = Path.GetDirectoryName(location);
70 var watcher =
new FileSystemWatcher(folder);
71 watcher.Filter = Path.GetFileName(location);
73 watcher.Changed += (
s, args) => {
74 if (args.ChangeType != WatcherChangeTypes.Changed)
78 var cacheEntry = _cachedAssemblies[location];
79 var fileInfo =
new FileInfo(location);
80 if (cacheEntry.LastWriteTime == fileInfo.LastWriteTime && cacheEntry.FileSize == fileInfo.Length)
84 cacheEntry.LastWriteTime = fileInfo.LastWriteTime;
85 cacheEntry.FileSize = fileInfo.Length;
86 cacheEntry.Assembly = null;
89 ThreadPool.QueueUserWorkItem(_ => {
90 Thread.Sleep(_autoRefreshDelay);
91 OnAssemblyUpdated(location);
95 watcher.EnableRaisingEvents =
true;
99 private void OnAssemblyUpdated(
string location) {
100 if (AssemblyUpdated == null || SelectedGrammar == null || SelectedGrammar.Location != location)
105 Assembly LoadAssembly(
string fileName) {
108 return Assembly.LoadFile(fileName);
EventHandler AssemblyUpdated
Maintains grammar assemblies, reloads updated files automatically.
Parsing.Grammar CreateGrammar()