Hello everyone, I'm starting to implement a simple daemon that basically fetches a file from an FTP location with the help of a BackgroundWorker component to kind of guarantee sort of thread safety there. Although I sort of feel I'm heading towards the right direction, I'm not completely familiar with the technologies involved, therefore not quite at ease with the whole application life cycle, say there's scenarios that I definitely don't know how to handle yet, namely, what to do with the stop event, what would happen if the service gets stopped while the worker is running, et cétera. I guess the following piece of code barely represents what I'm trying to achieve:
#region Daemon Events
protected override void OnStart(string[] args)
{
this.transferBackgroundWorker.RunWorkerAsync();
}
protected override void OnStop()
{
this.transferBackgroundWorker.CancelAsync(); // Thanks Wolfwyrd!
}
#endregion
#region BackgroundWorker Events
private void transferBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
worker.WorkerSupportsCancellation = true;
#region FTP Download
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(Daemon.FTP_HOST);
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.Credentials = new NetworkCredential(Daemon.FTP_USER, Daemon.FTP_PASS);
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
using(Stream ftpResponseStream = ftpResponse.GetResponseStream())
{
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine(ftpResponseStream);
sw.Close();
}
ftpResponse.Close();
}
#endregion
e.Result = "DEBUG: Download complete" + ftpResponse.StatusDescription;
}
private void transferBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
EventLog.WriteEntry("Exception caught: " + e.Error.Message);
}
else
{
EventLog.WriteEntry(e.Result.ToString());
}
}
#endregion
Any and every suggestion would be really appreciated. Thanks much in advance for the assistance.
Edit: just reimplemented the FTP file fetching.