【发布时间】:2010-10-21 04:07:47
【问题描述】:
我已经构建了一个 Windows 服务,但由于某种原因,当我启动该服务时,它会启动,然后又立即关闭。我试过用谷歌搜索为什么会这样。任何系统日志中都没有出现任何内容。这是我的服务的启动/停止代码。我希望因为我创建了一个文件侦听器,它应该保持运行。我错过了什么?
#region Declarations
private List<string> _keys = new List<string>();
private FileSystemWatcher _watcher;
private BackgroundWorker _worker;
static private bool _isBusy = false;
#endregion
#region Constructor
public FeedListener()
{
InitializeComponent();
}
#endregion
#region Start/Stop
protected override void OnStart(string[] args)
{
_keys.AddRange(new string[] { "csv", "xml", "zip", "rivx" });
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += new DoWorkEventHandler(BackgroundWorkerDoWork);
_worker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerProgressChanged);
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerRunWorkerCompleted);
_watcher = new FileSystemWatcher(AppSettings.Default.FTPRootPath, "*.*");
_watcher.IncludeSubdirectories = true;
_watcher.NotifyFilter = sysIO.NotifyFilters.DirectoryName | sysIO.NotifyFilters.FileName | sysIO.NotifyFilters.LastAccess | sysIO.NotifyFilters.CreationTime | sysIO.NotifyFilters.LastWrite;
_watcher.Created += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
_watcher.Changed += new sysIO.FileSystemEventHandler(fileCreatedOrChanged);
_watcher.EnableRaisingEvents = true;
TouchFiles();
}
protected override void OnStop()
{
_watcher.Dispose();
_watcher = null;
_worker.Dispose();
_worker = null;
}
#endregion
#region Event Handlers
void fileCreatedOrChanged(object sender, sysIO.FileSystemEventArgs e)
{
DTO.BackgroundWorkerEventArgs eventArgs = new DTO.BackgroundWorkerEventArgs();
sysIO.WatcherChangeTypes myType = e.ChangeType;
bool isValid = false;
foreach (string key in _keys)
{
if (Path.GetExtension(e.FullPath).Replace(".", "").Equals(key, StringComparison.CurrentCultureIgnoreCase))
isValid = true;
}
if (isValid)
{
try
{
eventArgs.PathAndFile = e.FullPath;
eventArgs.Key = Path.GetExtension(e.FullPath).ToLower().Replace(".", "");
eventArgs.FileName = Path.GetFileName(e.FullPath);
eventArgs.Path = Path.GetDirectoryName(e.FullPath);
eventArgs.UserName = Path.GetDirectoryName(e.FullPath).Replace(AppSettings.Default.FTPRootPath, "").Replace("\\", "");
FileInfo fileInfo = new FileInfo(eventArgs.PathAndFile);
// 1st attempt at stalling for the file lock due to slow write speeds...
while (IsFileLocked(fileInfo)) { /* nop */ }
// Wait until the thread is not busy...
//while (_worker.IsBusy) { /* nop */ }
while (_isBusy) { /* nop */ }
// Now, spin up a new thread and do the work on the file, based on file type...
_worker.RunWorkerAsync(eventArgs); // goes to BackgroundWorkerDoWork(object sender, DoWorkEventArgs e) //
}
catch (Exception ex)
{
string m = ex.Message;
}
}
}
void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
DTO.BackgroundWorkerEventArgs eventArgs = (DTO.BackgroundWorkerEventArgs)e.Argument;
RivWorks.FeedHandler.Handler handler = new RivWorks.FeedHandler.Handler();
_isBusy = true;
try
{
if (eventArgs.Key.Equals("csv", StringComparison.CurrentCultureIgnoreCase))
{
handler.ImportCSV(ref eventArgs);
}
if (eventArgs.Key.Equals("zip", StringComparison.CurrentCultureIgnoreCase))
{
handler.UnZip(ref eventArgs);
handler.ImportCSV(ref eventArgs);
}
}
catch (Exception ex)
{
string m = ex.Message;
_worker.ReportProgress(0);
}
finally
{
_isBusy = false;
_worker.ReportProgress(100);
if (_worker.CancellationPending)
{
e.Cancel = true;
}
}
}
void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("Cancelled.");
}
else if (e.Error != null)
{
Console.WriteLine(e.Error.Message);
}
else
{
Console.WriteLine("Successfully completed.");
}
TouchFiles();
}
#endregion
【问题讨论】:
-
当 FileListener 对象运行时,服务正在“工作”。它正在侦听文件。 :) 我添加了一个 try/catch 并将所有错误写到事件日志中。我发现我的一个路径(在 app.config 中)被设置为 UNC 而不是驱动器号。改变了这一点,瞧,它启动并做了它应该做的事情。上面的答案不是这种情况的正确答案。亚当的评论是最正确的。 (现在,答案似乎被删除了!)
标签: c# windows-services