简体   繁体   English

Windows Service不断寻找文件

[英]Windows Service constantly looking for files

Sorry if this is an stupid question, but I'm pretty new to Windows Services and want to make sure I understand the proper way to approach this situation. 抱歉,这是一个愚蠢的问题,但是我对Windows Services还是很陌生,并希望确保我了解解决此问题的正确方法。

I have a Windows Service that is meant to watch for files and if those files exist, it processes them. 我有一个Windows服务,用于监视文件,如果这些文件存在,它将处理它们。 I was looking through an old developer's code and they used Thread.Sleep() if files didn't exist. 我正在查看旧的开发人员的代码,如果文件不存在,他们将使用Thread.Sleep()。 I understand that this is bad practice and have seen it first-hand that this locks up the service. 我了解这是一种不好的做法,并且已经亲眼目睹了这可以锁定服务。

Here's a simplified example of my logic: 这是我的逻辑的简化示例:

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
    }
}

My first question: Is any sort of Delay or Pause even needed? 我的第一个问题:甚至需要任何形式的延迟或暂停吗? If I don't have any pause then this service will constantly look for files on a remote server. 如果我没有任何暂停,则此服务将不断在远程服务器上查找文件。 Is this something I have to worry about or is it a pretty light-weight process? 这是我要担心的事情,还是一个轻量级的过程?

Second question: If it would be better to pause instead of constantly hitting this server, is this a better approach or what would you recommend? 第二个问题:如果最好是暂停而不是不停地访问该服务器,这是更好的方法还是您会建议什么?

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

Thanks for your help! 谢谢你的帮助!

You can use timer to check desired files and folder. 您可以使用计时器检查所需的文件和文件夹。 Here is outline. 这是大纲。

  1. Add Timer in your service class (one that inherits ServiceBase class) 在服务类中添加Timer(一个继承ServiceBase类的计时器)

    private System.Timers.Timer myTimer; 私有System.Timers.Timer myTimer;

  2. Initialize timer in OnStart method. 在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. Define elapsed event handler. 定义经过的事件处理程序。

     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