我创建了一个C#Windows服务应用程序,该应用程序启动一个FileSystemWatcher
来监视创建文件的目录。当找到该文件时,我实例化一个自定义类来解析文件(CSV)并用它的内容调用Web服务。该服务有点异步,并返回一个唯一的数字,必须用于随后的调用来检查其进度。在我的流程类中,我创建了一个计时器来持续检查工作是否完成。我是dispose
ing和close
ing我的计时器,当我完成它,但我只是想确保我的类将垃圾收集,我不会有任何内存泄漏。使用FileSystemWatcher和Timer进行Windows服务 - 确保一切都得到处理
的代码看起来像这样(剪断,为了简洁):
我的主要服务类:
protected override void OnStart(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "path";
watcher.Filter = "file";
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.EnableRaisingEvents = true;
}
static void watcher_Created(object sender, FileSystemEventArgs e)
{
FileProcessor p = new FileProcessor();
p.Process(e.FullPath);
//Will this instance of p stick around until the timer within it is finished?
}
FileProcessor.cs
class FileProcessor
{
private System.Timers.Timer timer = new System.Timers.Timer();
private string id;
public FileProcessor()
{
timer.Elapsed += new ElapsedEventHandler(OnTimer);
timer.Enabled = false;
timer.AutoReset = true;
}
public void Process(string filename)
{
//Read file <snipped>
//Call web service and get id
id = CallWebService();
//Create a timer for 10 seconds and start it
timer.Interval = 10000;
timer.Enabled = true;
}
private bool IsFinished(string id)
{
//Call web service to see if job is finished, true if finished
//<snipped>
}
private void ProcessResults()
{
//Job is finished, process results
//Call cleanup method to dispose of timer
Cleanup();
}
private void OnTimer(object source, ElapsedEventArgs e)
{
if (!IsFinished(id))
{
//Keep timer running, check result again next timer event
return;
}
else
{
//Stop timer
timer.Stop();
//Process Results
ProcessResults(response);
}
}
private void Cleanup()
{
timer.Close();
timer.Dispose();
}
}
我的问题是我应该“p”的实例在我的计时器被销毁之前(不是被GC'ed)?它会被毁坏吗?我的FileProcessor类是否需要实现IDisposable,以便我可以将它包装在使用块中?我并不担心这是单线程的,因为我只希望它每天处理一个文件,并且完成该过程不应超过10分钟,然后返回到下一个要创建的文件。
是的,好东西 - 也调查'try/finally'块。 –
如何通知我的主服务类(称为FileProcessor的类)它已完成? – Jay
Jay,如果您需要事件帮助,请查看http://msdn.microsoft.com/zh-cn/library/aa645739(v=vs.71).aspx –