窗口服务行为怪异 [英] windows service strange behavior
问题描述
我实现Windows服务事件日志
和 FileSystemWatcher的
这会在特定的目录更改并写入信息到 MyLog
。
I implemented windows service with eventLog
and FileSystemWatcher
that looks for changes in specific directory and writes messages into MyLog
.
奇怪的事1:结果
我通过installUtil.exe安装(因为VS2012没有安装模板),并在某些情况下,当我去服务,开始我得到的服务:
strange thing 1:
I install it via installUtil.exe (since the VS2012 doesn't have installer templates) and in some situations when I go to "Services" and start the service I get:
本地计算机上的[服务名称]服务启动,然后停止。如果他们不被其他服务或程序使用的一些服务自动停止。
The [service name] service on local computer started and then stopped. Some Services stop automatically if they are not in use by another services or programs.
我已经看过的这个问题。从这个职位2 answeres为什么它可以是这样:
I've already seen this question. 2 answeres from this post why it can be so:
1)没有螺纹的OnStart开始()
法。结果
我使用设计,并设置大部分属性在属性窗口中,我从来没有手动启动任何线程,但在某些情况下,一切工作,所以我觉得这是不是这样的。
1) There is no thread starting in OnStart()
method.
I use the designer and set most of the properties in the Properties window and I never started any thread manually, but in some cases everything was working, so I think this is not the case.
2)例外的OnStart()
方法occures。我认为这不是因为我不更改代码的情况。我刚刚卸载,构建并重新安装相同的服务,并在运行某些情况下,有些不是。
2) An exception occures in OnStart()
method. I think it's not the case cause I don't change the code. I just uninstall, build and install again the same service and in some cases it runs, in some not.
当我被卡住了mabby这个东西我注意到2小时该事件日志
的来源
属性是太长:FilesMonitoringServices。我把它改成MonitorSource一切都开始工作。比我重新安装了它cauple的时候,得到了同样的警告如上述。我又换了来源
属性,现在服务运行。结果
这是第一次奇怪的事情。
When I was stuck for mabby 2 hours with this thing I noticed that the Source
property of eventLog
is too long: "FilesMonitoringServices". I changed it to "MonitorSource" and everything started to work. Than I reinstalled it cauple of times and got the same warning as the above. I changed the Source
property again and now the service runs.
This is the first strange thing.
奇怪的事2:更糟。即使运行时,它仅记录的OnStart()
和调用OnStop()
的方法,我的意思是FileSystemWatcher的事件处理程序从未excutes 。这很奇怪,因为今天我重新安装了这个服务mabby一百次和3次是工作,但之后我再次重新安装它,它采空。我没有任何改变reinstallations是在之间的代码。
strange thing 2: worse. Even if it runs it logs only OnStart()
and OnStop()
methods, I mean the fileSystemWatcher event handler never excutes. It is strange because today I reinstalled this service mabby hundred times and 3 times it was working but after I reinstalled it once again it stoped. And I haven't changed the code between the reinstallations at all.
下面是我的课(MonitoringService)继承 ServiceBase
的方法和构造器:
Here is the methods and constructor from my class (MonitoringService) that inherits ServiceBase
:
public MonitoringService()
{
InitializeComponent();
if (!EventLog.SourceExists(eventLog.Source))
{
EventLog.CreateEventSource(eventLog.Source, eventLog.Log);
}
// haven't changed it between the reinstallations
fileWatcher.Path = @"path";
}
protected override void OnStart(string[] args)
{
fileWatcher.EnableRaisingEvents = true;
eventLog.WriteEntry("start", EventLogEntryType.Information);
base.OnStart(args);
}
protected override void OnStop()
{
fileWatcher.EnableRaisingEvents = false;
fileWatcher.Dispose();
eventLog.WriteEntry("stop", EventLogEntryType.Information);
base.OnStop();
}
和文件系统观察事件处理程序:
And file system watcher event handler:
private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{
using (var conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
var productId = Convert.ToInt32(Regex.Match(e.Name, @"\d+").Value);
const string cmd = "UPDATE Products SET ImageModifiedDate=@date WHERE ProductId=@productId";
using (var command = new SqlCommand(cmd, conn))
{
command.Parameters.AddWithValue("@productId", productId);
command.Parameters.AddWithValue("@date", DateTime.Now);
command.ExecuteNonQuery();
}
}
eventLog.WriteEntry(string.Format("{0} has been changed: {1}", e.Name, DateTime.Now), EventLogEntryType.Information);
}
问:在我看来,这种行为是不是我的代码,而是由操作系统设置引起的。 ?它可以是这样
Question: it seems to me that this behavior is caused not by my code but rather by operation system settings . Can it be so?
* *编辑:刚刚发现更具体的东西:
1)如果显示消息(当我想启动该服务):
1) If it shows the message (when I want to start the service):
The [service name] service on local computer started and then stopped. ....
我需要改变来源
事件日志
,重新编译和安装。而这一消息将不会出现; 。mabby下次
I need to change Source
property of eventLog
, rebuild and reinstall. And this message will not show up; mabby next time.
2)我有以下文件夹层次结构:图像/ PROD-图像
。 图片
和 PROD-图像
目录中都包含的图像文件。当服务乳宁和我改变从 PROD-图像的图像
文件夹消息被写入日志,因为我想和更新数据库。但有此事件发生后,服务将停止! (我检查这3次)。当我重新启动,并再次重复这几次它更新的数据库,写日志,在3D时代,我得到
2) I have the following folders hierarchy: images/prod-images
. images
and prod-images
directories both contain image files. When the service is runing and I change the image from prod-images
folder the message is written into the log as I wanted and the database is updated. But after one this event the service stops! (I checked this 3 times). And when I restart it and repeat this again a couple of times it updates database, writes logs and on the 3d time I get
The [service name] service on local computer started and then stopped. ....
但是,这不是最好的部分)如果我改变是在图像图片
目录我能做到这一点了多次,服务不停止。
But this is not the best part) If I change the image that is in images
directory I can do it multiple times and the service doesn't stop. (only images from images/prod-images
are bound to entries in the database).
所以(从图像/ PROD-图像
绑定到数据库中的条目仅适用于图像),mabbe这功能莫名其妙referes来访问数据库
So, mabbe this feature somehow referes to the database accessing?
编辑2:在Visual Studio中我使用 DEBUG - >附加到进程
调试服务。我设置的断点和改变形象。首次执行事件处理程序完美:在更新数据库并写入日志消息。但比我继续按F11(步入),并且该事件处理程序执行第二次。在行
Edits 2: in visual studio I use DEBUG -> Attach to Process
to debug the service. I set up the breakpoints and change the image. First time the event handler executes flawlessly: the database is updated and the log message is written. But than I continue to press F11 (Step Into) and this event handler executes second time. At the line
var productId = Convert.ToInt32(Regex.Match(e.Name, @"\d+").Value);
我得到 FormatException
是未处理。此后,我停止调试和维修站!就是这样:异常事件处理程序occures。
I get "FormatException
was unhandled". After this I stop debugging and the service stops! That's it: the exception occures in event handler.
你有为什么执行第二次什么想法?谢谢!
Do You have any idea why it executes second time? Thanks!
PS 我已经submited DavutGürbüz答案,因为他指着我在正确的方向。结果
< STRONG>无论如何,检查出我自己的答案来解释实际问题。
P.S. I've already submited Davut Gürbüz answer cause he pointed me in the right direction.
Anyway, check out my own answer that explains the actual problem.
推荐答案
如果你有启停错误,这意味着你必须构造一个错误。
If you got start-stop error, this means you have an error in constructor.
将一个尝试捕捉到你的构造函数。您可以登录catch块到EventLog错误。
Put a try catch into your ctor. You may log the error to eventlog in catch block.
除了这个,我创建一个主要方法,并开始赢服务作为一个控制台应用程序。如果我的主要方法获取服务的实例我也可以调试。
Beside this I create a main method and start win service as a console app. If I get an instance of service in my main method I can also Debug it.
//You should select Console Application from Application properties
static void Main(string[] args)
{
MyWindowsService service = new MyWindowsService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
希望帮助
Hope helps
这篇关于窗口服务行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!