forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileWatcher.cs
More file actions
86 lines (73 loc) · 2.24 KB
/
FileWatcher.cs
File metadata and controls
86 lines (73 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Threading;
using ScriptCs.Contracts;
namespace ScriptCs.Command
{
public sealed class FileWatcher : IDisposable
{
private readonly object _timerLock = new object();
private readonly string _file;
private readonly int _intervalMilliseconds;
private readonly IFileSystem _fileSystem;
private DateTime _lastWriteTime;
private Timer _timer;
public FileWatcher(string file, int intervalMilliseconds, IFileSystem fileSystem)
{
Guard.AgainstNullArgument("fileSystem", fileSystem);
_file = file;
_intervalMilliseconds = intervalMilliseconds;
_fileSystem = fileSystem;
}
public event EventHandler Changed;
public void Start()
{
lock (_timerLock)
{
if (_timer != null)
{
return;
}
_lastWriteTime = _fileSystem.GetLastWriteTime(_file);
_timer = new Timer(_ => CheckLastWriteTime(), null, Timeout.Infinite, Timeout.Infinite);
_timer.Change(_intervalMilliseconds, Timeout.Infinite);
}
}
public void Stop()
{
lock (_timerLock)
{
if (_timer == null)
{
return;
}
_timer.Dispose();
_timer = null;
}
}
public void Dispose()
{
Stop();
}
private void CheckLastWriteTime()
{
lock (_timerLock)
{
if (_timer == null)
{
return;
}
var previousLastWriteTime = _lastWriteTime;
_lastWriteTime = _fileSystem.GetLastWriteTime(_file);
if (_lastWriteTime != previousLastWriteTime)
{
var changed = this.Changed;
if (changed != null)
{
changed.Invoke(this, EventArgs.Empty);
}
}
_timer.Change(_intervalMilliseconds, Timeout.Infinite);
}
}
}
}