我正在尝试创建我的第一个Windows服务,但太悲哀了……在我从services.msc手动启动服务后,出现消息“服务在本地计算机上启动,然后停止。有些服务自动停止是因为它们没有工作要做”。
我确信在我的代码中一定有一些错误...
namespace ConvertService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
this.ServiceName = "ConvertService";
this.EventLog.Log = "Application";
}
static void main()
{
ServiceBase.Run(new Service1());
}
protected override void OnStart(string[] args)
{
Process pMP3 = new Process();
pMP3.StartInfo.UseShellExecute = false;
pMP3.StartInfo.RedirectStandardOutput = true;
pMP3.StartInfo.FileName = @"d:\...path...\converter.exe";
pMP3.StartInfo.Arguments = @"d:\...path...\tempamr.amr " + @"d:\...path...\tempmp3.mp3 " + @"-cmp3";
pMP3.Start();
pMP3.WaitForExit();
Process pWAV = new Process();
pWAV.StartInfo.UseShellExecute = false;
pWAV.StartInfo.RedirectStandardOutput = true;
pWAV.StartInfo.FileName = @"d:\...path...\converter.exe";
pWAV.StartInfo.Arguments = @"d:\...path...\tempmp3.mp3 " + @"d:\...path...\tempwav.wav " + @"-cwav";
pWAV.Start();
pWAV.WaitForExit();
}
protected override void OnStop()
{
}
}}
如果我犯了愚蠢的错误,请原谅我。这是我的第一个Windows服务。
PS。我已经勾选了“允许服务与桌面交互”。
发布于 2011-08-19 02:21:40
检查以确保运行服务的帐户可以访问这些文件(包括对.wav和.mp3文件的写访问权限)。
您的代码还可能导致未处理的异常。我不确定,但这可能在事件日志中可见。您还可以让您的服务显式地将消息写到事件日志中(就像在发生异常的情况下一样);请查看此链接:http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
发布于 2011-08-19 02:19:52
您没有为OnStart方法创建正在运行的线程。基本上,服务管理器调用OnStart来启动服务,该调用需要在大约15秒内完成。在内部,您应该创建一个具有循环的线程,该线程随时间推移实际调用您的代码。如下所示:
protected CancellationTokenSource _tokenSource = null;
protected Task _thread = null;
protected override void OnStart(string[] args)
{
_tokenSource = new CancellationTokenSource();
_thread = Task.Factory.StartNew(() => DoMyServiceLogic(), TaskCreationOptions.LongRunning, _tokenSource);
}
protected override void OnStop()
{
_tokenSource.Cancel();
}
protected void DoMyServiceLogic()
{
while(!_tokenSource.Token.IsCancellationRequested)
{
// Do Stuff
}
}您的服务并没有真正遵循这种模式;您没有连续地做事情,这应该更像是一个控制台程序。
实际上,这是因为您的服务在您完成OnStart方法后立即停止了任何操作。这就像你在控制台程序中完成Main时发生的事情--应用程序刚刚退出。
发布于 2011-08-19 02:22:09
打开eventvwr.msc。在那里您将看到有关windows服务停止工作的原因的异常详细信息。顺便说一句,您应该尽快离开OnStart方法,因为您只有30秒的时间来完成OnStart方法。在MSDN上有一篇很好的文章描述了“如何调试”Windows Services。
https://stackoverflow.com/questions/7112093
复制相似问题