在执行其他操作时查看文件

时间:2018-05-24 18:11:41

标签: c# .net multithreading asynchronous file-watcher

我正在实现一个应该执行以下操作的winform应用程序:

  1. OnLoad,打开一个XML文件,在查看文件的任何新更改(传入的新信息)时读取所需信息
  2. 计时器根据XML文件中提供的信息的性质执行某些操作。请注意,操作的性质取决于XML文件的内容
  3. 实现这一目标的最佳方法是什么?两个线程?异步?一些起点将非常感激。

1 个答案:

答案 0 :(得分:0)

我认为你需要这样的结构。首先,您阅读XML文件并配置自定义MyConfigurationClass对象。在此之后,您可以配置FileSystemWatcher对象。最后,您可以使用所需的时间间隔配置任务计划对象。

public partial class MainWindow : Window
{
    MyConfigurationClass configuration;

    string filePath = @"./some.xml";
    FileSystemWatcher fileWatcher = new FileSystemWatcher();
    System.Timers.Timer timer = new System.Timers.Timer();

    public MainWindow()
    {
        // First read action action for 
        var task = Task.Run(() => ReadXML());

        InitializeComponent();

        FileWatherConfigure();

        TimerConfigure(task.Result);
    }

    private void FileWatherConfigure()
    {
        fileWatcher.Path = System.IO.Path.GetDirectoryName(filePath);
        fileWatcher.Filter = System.IO.Path.GetFileName(filePath);
        fileWatcher.Changed += FileWatcher_Changed;
        fileWatcher.EnableRaisingEvents = true;
    }

    private void TimerConfigure(SomeClass someClass)
    {
        timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        timer.Interval = configuration.TimeInterval.TotalMilliseconds;
        timer.Enabled = true;
    }

    private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));

        SomeClass someClass = ReadXML();
        // Do whatever you want file change
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        timer.Stop();
        try
        {
            // Schedule Operation
        }
        catch (Exception ex)
        {

        }
        timer.Start();

    }

    private SomeClass ReadXML()
    {
        // Read file and do what ever you want
    }
}

public class SomeClass
{
    // Data from XML
}

public class MyConfigurationClass
{
    public TimeSpan TimeInterval { get; set; }
}