C#文件监控时创建文件引发多次改变事件的解决办法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
解决方案代码
[csharp]view plaincopyprint?
ing System;
ing System.Collections.Generic;
ing System.Linq;
ing System.Text;
ing System.IO;
ing System.Threading;
7.
space ShareReadFile
9.{
10. public delegate void FileSystemEvent(String path);
11.
12. public interface IDirectoryMonitor
13. {
14. event FileSystemEvent Change;
15. void Start();
16. }
17.
18. public class DirectoryMonitor : IDirectoryMonitor
19. {
20. private readonly FileSystemWatcher m_fileSystemWatcher = new File
SystemWatcher();
21. private readonly Dictionary
ew Dictionary
22. private readonly Timer m_timer;
23. private bool m_timerStarted = false;
24.
25. public DirectoryMonitor(string dirPath)
26. {
27. m_fileSystemWatcher.Path = dirPath;
28. m_fileSystemWatcher.IncludeSubdirectories = false;
29. m_fileSystemWatcher.Created += new FileSystemEventHandler(OnC
hange);
30. m_fileSystemWatcher.Changed += new FileSystemEventHandler(OnC
hange);
31.
32. m_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeou
t.Infinite);
33. }
34.
35. public event FileSystemEvent Change;
36.
37. public void Start()
38. {
39. m_fileSystemWatcher.EnableRaisingEvents = true;
40. }
41.
42. private void OnChange(object sender, FileSystemEventArgs e)
43. {
44. // Don't want other threads messing with the pending events r
ight now
45. lock (m_pendingEvents)
46. {
47. // Save a timestamp for the most recent event for this pa
th
48. m_pendingEvents[e.FullPath] = DateTime.Now;
49.
50. // Start a timer if not already started
51. if (!m_timerStarted)
52. {
53. m_timer.Change(100, 100);
54. m_timerStarted = true;
55. }
56. }
57. }
58.
59. private void OnTimeout(object state)
60. {
61. List
62.
63. // Don't want other threads messing with the pending events r
ight now
64. lock (m_pendingEvents)
65. {
66. // Get a list of all paths that should have events thrown
67. paths = FindReadyPaths(m_pendingEvents);
68.
69. // Remove paths that are going to be used now
70. paths.ForEach(delegate(string path)
71. {
72. m_pendingEvents.Remove(path);
73. });
74.
75. // Stop the timer if there are no more events pending
76. if (m_pendingEvents.Count == 0)
77. {
78. m_timer.Change(Timeout.Infinite, Timeout.Infinite);
79. m_timerStarted = false;
80. }
81. }
82.
83. // Fire an event for each path that has changed
84. paths.ForEach(delegate(string path)
85. {
86. FireEvent(path);
87. });
88. }
89.
90. private List
events)
91. {
92. List