C# 在执行其他操作时查看文件
我正在实现一个winform应用程序,它应该执行以下操作:C# 在执行其他操作时查看文件,c#,.net,multithreading,asynchronous,file-watcher,C#,.net,Multithreading,Asynchronous,File Watcher,我正在实现一个winform应用程序,它应该执行以下操作: OnLoad,打开一个XML文件,读取所需信息,同时查看文件的任何新更改(传入的新信息) 根据XML文件中提供的信息的性质执行某些操作的计时器。请注意,操作的性质取决于XML文件的内容 实现这一目标的最佳方式是什么?两条线?异步的?如果您能提供一些起点,我们将不胜感激 我想你需要这样的结构。首先,您读取XML文件并配置自定义的MyConfigurationClass对象。在此之后,您可以配置FileSystemWatcher对象。最后,
实现这一目标的最佳方式是什么?两条线?异步的?如果您能提供一些起点,我们将不胜感激 我想你需要这样的结构。首先,您读取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; }
}
开始研究。我知道如何使用FileSystemWatcher监视文件更改。我不确定如何将结果传达给正在进行的行动?