“new System.Timers.ElapsedEventHandler(DoStuff)”调用无法正常工作

我试图在C#中创建监视文件夹aplicaction,它将在新文件到达时执行操作。 由于监视文件夹在GPFS共享上,我无法使用FileSystemWatcher(在NTFS中对我来说很好)。 所以我将应用程序基于其他同事解决方案 。 该应用程序很好地显示“计时器启动”消息,但它涉及到

timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff); 

它没有调用DoStuff方法 – “启动新文件proc”消息从不显示。 我做错了什么? 这是完整的代码:

 namespace MonitorFolderActivity { public partial class frmMain : Form { List fileList = new List(); System.Timers.Timer timer; DateTime LastChecked; public frmMain() { InitializeComponent(); } private void abortAcitivityMonitoring() { btnStart_Stop.Text = "Start"; txtActivity.Focus(); } private void startActivityMonitoring(string sPath) { if (sPath.Length  -1) timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds; else timer.Interval = 1; timer.Start(); } private delegate void AddLogText(string text); private void TS_AddLogText(string text) { if (this.InvokeRequired) { AddLogText del = new AddLogText(TS_AddLogText); Invoke(del, text); } else { txtActivity.Text += text; } } private void btnStart_Stop_Click(object sender, EventArgs e) { if (btnStart_Stop.Text.Equals("Start")) { btnStart_Stop.Text = "Stop"; startActivityMonitoring(txtFolderPath.Text); } else { btnStart_Stop.Text = "Start"; stopActivityMonitoring(); } } private void lblActivity_Click(object sender, EventArgs e) { } private void lblToMonitor_Click(object sender, EventArgs e) { } } } 

您的代码中几乎没有问题。

首先 ,您没有设置计时器应该经过的时间,这意味着它将读取默认值

100毫秒

其次,你没有启动你的计时器。 您需要在此方法startActivityMonitoring else语句中将此行添加到您的代码中。

timer.Interval = yourdesiredinterval;

timer.Start();

第三,当您正在停止和启动时(通过代码的外观),您不应该在每次调用startActivityMonitoring方法时创建新的计时器。 相反,你应该这样做

 If(timer == null) { timer = new System.Timers.Timer(); timer.AutoReset = false; timer.Interval = yourinterval; timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff); } timer.Start(); 

在你的else子句中,你永远不会启动计时器。 这是一个修复:

 else { TS_AddLogText(string.Format("Timer starts\r\n")); timer = new System.Timers.Timer(); timer.AutoReset = false; timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff); timer.Start(); }