0

I have one requirement in my C# project. I have to scan a files only for certain period of time and it will stop scanning after some hours. For continuous watching a file, I used FileSystemWatcher() class and this class continuous will watch a files if any files renamed, created, deleted. Now, my requirement is stop a scanning files after some time. I started a StartWatcher() method to start a FileSystemWatcher() class. I got a time in sec. How will I call stopWatcher() method after certain period of time.

Any quick idea ??

m_monitor.StartWatcher();

// code in C# so that I can call StopWatcher after some period of time.

m_monitor.StopWatcher();
4

2 回答 2

1

解决这个问题的方法不止一种。一种简单的方法是使用Timer,例如:

private Timer myTimer = null;
public void YourMethod()
{
  m_monitor.StartWatcher();
  myTimer = new Timer(60000); // 60 seconds
  myTimer.AutoReset = false; // only trigger once
  myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
  myTimer.Enabled = true;
}

private static void OnTimedEvent(object source, ElapsedEventArgs e) 
{
  m_monitor.StopWatcher();
}

尚未对其进行测试,但这应该会将您推向正确的方向。

于 2013-04-29T11:29:56.817 回答
0

您可以使用 TPL(任务并行库)的延迟。

public async Task StartFileSystemWatcher()
        {
            m_monitor.StartWatcher();
            await Task.Delay(Timeout);
            m_monitor.StopWatcher();
        }
于 2013-04-29T11:36:57.873 回答