[英]Why Windows Service stops for no reason? using C#.net
我使用 C#.net 构建的 windows 服务
它只是使用命令行调用另一个软件。
调用软件已完成,并且 100% 确定它在正常的 forms 应用程序中工作。
在我的情况下,当我启动服务时它启动正常,运行一个计时器并在这个计时器内运行命令行。
出于某种原因,我无法找到为什么服务在第二次调用计时器后自行停止。
我追踪了问题,但找不到它停止的原因以及如何解决它。
我将服务简化为调用“PING”命令。 仍然停止服务。
这是我的代码,如果有人能告诉我问题出在哪里以及如何解决,我将不胜感激。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Timers;
namespace cProcessor
{
public partial class cProcessorSrv : ServiceBase
{
EventLog eventLog1;
public cProcessorSrv()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("cPr"))
{
System.Diagnostics.EventLog.CreateEventSource(
"cPr", "cPrLog");
}
eventLog1.Source = "cPr";
eventLog1.Log = "cPrLog";
}
protected override void OnStart(string[] args)
{
try
{
eventLog1.WriteEntry("OnStart");
Timer timer = new Timer();
timer.Interval = 15 * 1000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
catch(Exception ex)
{
eventLog1.WriteEntry("Exception : " + ex.ToString());
}
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
try
{
eventLog1.WriteEntry("OnTimer");
string command = "ping yahoo.com";
string workingFolder = @"c:\";
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true; ;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = workingFolder;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object snd, DataReceivedEventArgs e) =>
{
if (e.Data.Contains("INFO FileTreeXmiWriter") || e.Data.Contains("INFO FileTreeReader") || e.Data.Contains("error"))
{
eventLog1.WriteEntry("output>>" + e.Data);
}
};
process.BeginOutputReadLine();
process.ErrorDataReceived += (object snd, DataReceivedEventArgs e) =>
{
eventLog1.WriteEntry("error>>" + e.Data);
};
process.BeginErrorReadLine();
process.WaitForExit();
eventLog1.WriteEntry("ExitCode: " + process.ExitCode.ToString());
process.Close();
/* */
}
catch(Exception ex)
{
eventLog1.WriteEntry("Exception :" + ex.ToString());
}
}
}
}
这是日志结果(只有 3 个信息)
OnStart
OnTimer
error>>
我像这样调试了 Windows 服务代码,发现它在e.Data.Contains("INFO FileTreeXmiWriter")
上崩溃,因为e.Data
是 null。 一种解决方案是在运行 IF 语句之前添加 null 检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.