retag
[mcs.git] / nunit24 / ClientUtilities / util / AssemblyWatcher.cs
blob557c7b11144cae5421a1d025e2525c0eab545453
1 // ****************************************************************
2 // This is free software licensed under the NUnit license. You
3 // may obtain a copy of the license as well as information regarding
4 // copyright ownership at http://nunit.org/?p=license&r=2.4.
5 // ****************************************************************
7 using System;
8 using System.IO;
9 using System.Text;
10 using System.Timers;
11 using System.Collections;
13 namespace NUnit.Util
15 /// <summary>
16 /// AssemblyWatcher keeps track of one or more assemblies to
17 /// see if they have changed. It incorporates a delayed notification
18 /// and uses a standard event to notify any interested parties
19 /// about the change. The path to the assembly is provided as
20 /// an argument to the event handler so that one routine can
21 /// be used to handle events from multiple watchers.
22 /// </summary>
23 public class AssemblyWatcher
25 FileSystemWatcher[] fileWatcher;
26 FileInfo[] fileInfo;
28 protected System.Timers.Timer timer;
29 protected string changedAssemblyPath;
31 public delegate void AssemblyChangedHandler(String fullPath);
32 public event AssemblyChangedHandler AssemblyChangedEvent;
34 public AssemblyWatcher( int delay, string assemblyFileName )
35 : this( delay, new string[]{ assemblyFileName } ) { }
37 public AssemblyWatcher( int delay, IList assemblies )
39 fileInfo = new FileInfo[assemblies.Count];
40 fileWatcher = new FileSystemWatcher[assemblies.Count];
42 for( int i = 0; i < assemblies.Count; i++ )
44 fileInfo[i] = new FileInfo( (string)assemblies[i] );
46 fileWatcher[i] = new FileSystemWatcher();
47 fileWatcher[i].Path = fileInfo[i].DirectoryName;
48 fileWatcher[i].Filter = fileInfo[i].Name;
49 fileWatcher[i].NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite;
50 fileWatcher[i].Changed+=new FileSystemEventHandler(OnChanged);
51 fileWatcher[i].EnableRaisingEvents = false;
54 timer = new System.Timers.Timer( delay );
55 timer.AutoReset=false;
56 timer.Enabled=false;
57 timer.Elapsed+=new ElapsedEventHandler(OnTimer);
60 public FileInfo GetFileInfo( int index )
62 return fileInfo[index];
65 public void Start()
67 EnableWatchers( true );
70 public void Stop()
72 EnableWatchers( false );
75 private void EnableWatchers( bool enable )
77 foreach( FileSystemWatcher watcher in fileWatcher )
78 watcher.EnableRaisingEvents = enable;
81 protected void OnTimer(Object source, ElapsedEventArgs e)
83 lock(this)
85 PublishEvent();
86 timer.Enabled=false;
90 protected void OnChanged(object source, FileSystemEventArgs e)
92 changedAssemblyPath = e.FullPath;
93 if ( timer != null )
95 lock(this)
97 if(!timer.Enabled)
98 timer.Enabled=true;
99 timer.Start();
102 else
104 PublishEvent();
108 protected void PublishEvent()
110 if ( AssemblyChangedEvent != null )
111 AssemblyChangedEvent( changedAssemblyPath );