C# 本地计算机上的 Windows 服务启动然后停止错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12209075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows service on Local Computer started and then stopped error
提问by Blackator
Usually, I get this error: (The "service name" service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other service or programs) when there's something wrong with my code, like non-existing drive paths, etc. The windows service will not start.
通常,我会收到此错误:(本地计算机上的“服务名称”服务启动然后停止。如果其他服务或程序未使用某些服务会自动停止)当我的代码有问题时,例如不存在驱动器路径等。windows 服务将不会启动。
I have a windows service that backs up folder/files, to a location if it reached the size limit. Details are all provide by an XML Configuration that the windows service reads on start. I have a separate windows forms that has a button that does exactly what my windows service's onstart is doing. I use my windows forms for debugging the code before I put it in my windows service.
我有一个 Windows 服务,可以将文件夹/文件备份到一个位置,如果它达到了大小限制。详细信息全部由 Windows 服务在启动时读取的 XML 配置提供。我有一个单独的 Windows 窗体,它有一个按钮,它完全执行我的 Windows 服务的 onstart 正在执行的操作。在将代码放入 Windows 服务之前,我使用 Windows 窗体调试代码。
When I start my windows forms. It does what it suppose to do. When I put my code in the windows service OnStart() method the error showed up.
当我开始我的窗体时。它会做它应该做的事情。当我将代码放入 Windows 服务 OnStart() 方法时,错误出现了。
Here's my code:
这是我的代码:
protected override void OnStart(string[] args)
{
private static string backupConfig = @"D:\LogBackupConfig\backupconfig.xml";
private static string serviceStat = @"D:\LogBackupConfig\Status.txt";
private static string fileFolderStat = @"D:\LogBackupConfig\FileFolderStat.txt";
protected override void OnStart(string[] args)
{
if (File.Exists(backupConfig))
{
FileSystemWatcher watcher = new FileSystemWatcher();
XmlTextReader reader = new XmlTextReader(backupConfig);
XmlNodeType type;
List<string> listFile = new List<string>();
string fileWatch = "";
//this loop is for reading XML elements and assigning to variables
while (reader.Read())
{
type = reader.NodeType;
if (type == XmlNodeType.Element)
{
if (reader.Name == "File")
{
reader.Read();
fileWatch = reader.Value;
}
else if (reader.Name == "Folder")
{
reader.Read();
fileWatch = reader.Value;
}
}
}
reader.Close();
watcher.Path = fileWatch;
watcher.Filter = "*.*";
//this loop reads whether the service will watch a file/folder
XmlTextReader reader1 = new XmlTextReader(backupConfig);
while (reader1.Read())
{
type = reader1.NodeType;
if (type == XmlNodeType.Element)
{
if (reader1.Name == "File")
{
watcher.IncludeSubdirectories = false;
watcher.Changed += new FileSystemEventHandler(OnChangedFile);
}
else if (reader1.Name == "Folder")
{
watcher.IncludeSubdirectories = true;
watcher.Changed += new FileSystemEventHandler(OnChangedFolder);
}
}
}
reader1.Close();
watcher.EnableRaisingEvents = true;
}
else
{
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("File not found. Please start the Log Backup UI first.");
sw.Close();
}
}
I don't know what keeps the windows service not starting, the windows form simulator worked fine. What seems to be the problem?
我不知道是什么让 Windows 服务无法启动,Windows 窗体模拟器运行良好。似乎是什么问题?
UPDATE: After many trials I've noticed that using only a folder directory (w/out file), the windows service doesn't work. When I replaced the fileWatch variable with a specific file (including its directory), the windows service started. When I changed it back to a folder location, it didn't work. What I think is that folder locations doesn't work in a filewatcher.
更新:经过多次试验,我注意到仅使用文件夹目录(无文件),Windows 服务不起作用。当我用特定文件(包括其目录)替换 fileWatch 变量时,Windows 服务启动。当我将其改回文件夹位置时,它不起作用。我认为文件夹位置在文件观察器中不起作用。
When I tried creating a new windows service that watches a folder location, it worked.. However, when I tried the same location in my original windows service, it didn't work! I was mindf$#*ed! It seems that I have to create a new windows service and build the installer everytime I place a new code/function.. This way I can keep track where I get an error.
当我尝试创建一个监视文件夹位置的新 Windows 服务时,它起作用了。但是,当我在原始 Windows 服务中尝试相同的位置时,它不起作用!我很介意$#*ed!似乎每次我放置新代码/功能时,我都必须创建一个新的 Windows 服务并构建安装程序。这样我就可以跟踪出现错误的地方。
采纳答案by McGarnagle
If the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.
如果服务像这样启动和停止,则意味着您的代码抛出了未处理的异常。这很难调试,但有几个选项。
- Consult the Windows Event Viewer. Normally you can get to this by going to the computer/server manager, then clicking Event Viewer-> Windows Logs-> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
- Extract your program logic into a library class project. Now create two different versions of the program: a console app (for debugging), and the windows service. (This is a bit of initial effort, but saves a lot of angst in the long run.)
- Add more try/catch blocks and logging to the app to get a better picture of what's going on.
- 请参阅 Windows事件查看器。通常,您可以通过转到计算机/服务器管理器,然后单击Event Viewer-> Windows Logs-> Application 来实现此目的。您可以在此处查看引发异常的原因,这可能会有所帮助,但您不会获得堆栈跟踪。
- 将您的程序逻辑提取到库类项目中。现在创建两个不同版本的程序:控制台应用程序(用于调试)和 Windows 服务。(这是一些初步的努力,但从长远来看可以节省很多焦虑。)
- 添加更多 try/catch 块并记录到应用程序以更好地了解正在发生的事情。
回答by Sethu
Use Timer and tick event to copy your files.
使用计时器和滴答事件复制您的文件。
On start the service, start the time and specify the interval in the time.
在启动服务时,启动时间并指定时间间隔。
So the service is keep running and copy the files ontick.
因此该服务将继续运行并复制文件 ontick。
Hope it help.
希望有帮助。
回答by Quinton Bernhardt
You may want to unit test the initialization - but because it's in the OnStartmethod this is near to impossible. I would suggest moving the initialization code out into a separate class so that it can be tested or at least re-used in a form tester.
您可能想要对初始化进行单元测试 - 但因为它在OnStart方法中,这几乎是不可能的。我建议将初始化代码移到一个单独的类中,以便可以对其进行测试或至少在表单测试器中重新使用。
Secondly to add some logging (using Log4Netor similar) and add some verbose logging so that you can see details about runtime errors. Examples of runtime errors would be AccessViolationetc. especially if your service is running without enough privileges to access the config files.
其次添加一些日志记录(使用Log4Net或类似的)并添加一些详细的日志记录,以便您可以查看有关运行时错误的详细信息。运行时错误的例子是AccessViolation等等。特别是如果您的服务运行时没有足够的权限来访问配置文件。
回答by Eyal H
Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:
不确定这是否会有所帮助,但为了调试服务,您始终可以在 OnStart 方法中使用以下内容:
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
...
}
than you could attach your visual studio to the process and have better debug abilities.
比您可以将您的视觉工作室附加到流程并具有更好的调试能力。
hope this was helpful, good luck
希望这是有帮助的,祝你好运
回答by Alf K?re Lefdal
The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig.
运行该服务的帐户可能没有映射 D:-驱动器(它们是特定于用户的)。尝试共享目录,并在backupConfig.
Your watcherof type FileSystemWatcheris a local variable, and is out of scope when the OnStartmethod is done. You probably need it as an instance or class variable.
您watcher的类型FileSystemWatcher是一个局部变量,并且在OnStart方法完成时超出范围。您可能需要它作为实例或类变量。
回答by shah
Please check that you have registered all HTTP endpoints in the local mahcine's Access Control List (ACL)
请检查您是否已在本地机器的访问控制列表 (ACL) 中注册了所有 HTTP 端点
http://just2thepoint.blogspot.fr/2013/10/windows-service-on-local-computer.html
http://just2thepoint.blogspot.fr/2013/10/windows-service-on-local-computer.html
回答by Ben Anderson
I have found it very handy to convert your existing windows serviceto a consoleby simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it
我发现通过简单地使用以下内容更改您的程序,将您现有的Windows 服务转换为控制台非常方便。通过此更改,您可以通过在 Visual Studio 中调试或正常运行可执行文件来运行程序。但它也可以作为 Windows 服务工作。我还写了一篇关于它的博客文章
program.cs
程序.cs
class Program
{
static void Main()
{
var program = new YOUR_PROGRAM();
if (Environment.UserInteractive)
{
program.Start();
}
else
{
ServiceBase.Run(new ServiceBase[]
{
program
});
}
}
}
YOUR_PROGRAM.cs
你的程序.cs
[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
public YOUR_PROGRAM()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Start();
}
protected override void OnStop()
{
//Stop Logic Here
}
public void Start()
{
//Start Logic here
}
}
回答by PanosPlat
I came across the same issue. My service is uploading/receiving XMLS and write the errors to the Event Log.
我遇到了同样的问题。我的服务正在上传/接收 XMLS 并将错误写入事件日志。
When I went to the Event Log, I tried to filter it. It prompt me that the Event Log was corrupted.
当我转到事件日志时,我尝试对其进行过滤。它提示我事件日志已损坏。
I cleared the Event Log and all OK.
我清除了事件日志,一切正常。
回答by panini pitke
EventLog.Log should be set as "Application"
EventLog.Log 应设置为“应用程序”
回答by Emre Guldogan
Meanwhile, another reason :accidentally deleted the .configfile caused the same error message appears:
同时,另一个原因:不小心删除了.config文件导致出现同样的错误信息:
"Service on local computer started and then stopped. some services stop automatically..."
“本地计算机上的服务启动然后停止。一些服务自动停止......”

