多线程FileSystemWatcher监视本地文件夹已更改,计时器在网络关闭时处理,并在Window Service中再次Ping

时间:2012-10-27 09:14:43

标签: c# .net windows-services filesystemwatcher

默认情况下,本机编写的脚本会将文件保存到“本地/服务器路径”文件夹,但由于网络问题,两个文件夹都不同步。我已经使用FileSystemWatcher,DiffEngine,System.Timers和PingService编写了一个C#Window Service程序,如下面的编码来处理这个问题。 要监视本地文件夹OnChange Event,请在比较/复制到服务器路径之前Ping服务器IP是否成功,当Ping失败时,它将转到logtemp文件夹,系统计时器处理此命令并再次Ping,然后重新转储logtemp文件。

我不知道如何使用线程。当ping失败时,我的系统定时器代码应该在哪里?

protected override void OnStart(string[] args)
{  //all watcher config here// 
    watcher.Path = "path";
    watcher.NotifyFilter = NotifyFilters.LastWrite;
    watcher.Filter = "filename_company-Pg1_Product*";
    watcher.Changed += new FileSystemEventHandler(LogFileSystemChanges);
    watcher.EnableRaisingEvents = true;}

private void LogFileSystemChanges(object sender, FileSystemEventArgs e)
{ 
    FileInfo sourcepath = new FileInfo(e.FullPath);
    FileInfo destPath = new FileInfo(Path.Combine(dFile, e.Name));
    FileInfo _tempPath = new FileInfo(Path.Combine(tempPath, e.Name));

    if (PingService()) 
    //PingService Bool Type....Ping Specific IP Before Compare/Copy
    {
       if (!destPath.Exists) 
       {
          LogEvent(destPath + " DOES NOT EXIST!! ");
          CopyFunction.CopyFile(sourcepath, destPath, true, true);
       }
       else
       {
          if (BinaryDiff(sFile, Path.Combine(dFile, e.Name))) 
          //DiffEngine If Source & Diff are Different is TRUE.
          {
             CopyFunction.CopyFile(sourcepath, destPath, true, true);
          }
       }
       string msg = string.Format("Filename {0} are {1} now at {2} ", _
                    e.Name, e.ChangeType, DateTime.Now.ToString());
       LogEvent(msg);
       }
       else
       {
           CopyFunction.CopyFile(sourcepath, _tempPath, true, true);
       }
}

1 个答案:

答案 0 :(得分:0)

使用NServiceBus(他们称之为Saga)

它是一个开源项目,可让您万无一失地将代码与网络中断的情况进行隔离。

或者你只是问如何制作一个帖子?

如果有,请参阅MSDN on examples for creating threads