繁体   English   中英

Windows Service不断寻找文件

[英]Windows Service constantly looking for files

抱歉,这是一个愚蠢的问题,但是我对Windows Services还是很陌生,并希望确保我了解解决此问题的正确方法。

我有一个Windows服务,用于监视文件,如果这些文件存在,它将处理它们。 我正在查看旧的开发人员的代码,如果文件不存在,他们将使用Thread.Sleep()。 我了解这是一种不好的做法,并且已经亲眼目睹了这可以锁定服务。

这是我的逻辑的简化示例:

private Task _processFilesTask;
private CancellationTokenSource _cancellationTokenSource;

public Start()
{
   _cancellationTokenSource = new CancellationTokenSource();
   _processFilesTask = Task.Run(() => DoWorkAsync(_cancellationTokenSource.Token))
}

public async Task DoWorkAsync(CancellationToken token)
{
   while(!token.IsCancellationRequested)
   {
      ProcessFiles();
      //await Task.Delay(10000);
   }
}

public Stop()
{
   _cancellationTokenSource.Cancel();
   _processFilesTask.Wait();
}

private void ProcessFiles()
{
  FileInfo xmlFile = new DirectoryInfo(Configs.Xml_Input_Path).GetFiles("*.xml").OrderBy(p => p.CreationTime).FirstOrDefault();
  if(xmlFile != null)
    {
      //read xml
      //write contents to db
      //move document specified in xml to another file location
      //delete xml
    }
}

我的第一个问题:甚至需要任何形式的延迟或暂停吗? 如果我没有任何暂停,则此服务将不断在远程服务器上查找文件。 这是我要担心的事情,还是一个轻量级的过程?

第二个问题:如果最好是暂停而不是不停地访问该服务器,这是更好的方法还是您会建议什么?

public  async Task DoWorkAsync(CancellationToken token)
{
   while(!token.IsCancellationRequested)
   {
      ProcessFiles();
      await Task.Delay(TimeSpan.FromMilliseconds(10000), token).ContinueWith(_processFilesTask=> { });
   }
}

谢谢你的帮助!

您可以使用计时器检查所需的文件和文件夹。 这是大纲。

  1. 在服务类中添加Timer(一个继承ServiceBase类的计时器)

    私有System.Timers.Timer myTimer;

  2. 在OnStart方法中初始化计时器。

     protected override void OnStart(string[] args) { // Set the Interval to 1 seconds (1000 milliseconds). myTimer = new System.Timers.Timer(1000); // Hook up the Elapsed event for the timer. myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); myTimer.Enabled = true; } 
  3. 定义经过的事件处理程序。

     private void OnTimedEvent(object source, ElapsedEventArgs e) { //Write your file handling logic here. //Service will execute this code after every one second interval //as set in OnStart method. } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM