C#Windows服务 - 本地计算机上的服务已启动,然后停止?
我想创建我的第一个Windows服务,但很伤心......在我从services.msc手动启动服务之后,消息'本地计算机上的服务启动并停止。一些服务自动停止,是他们没有工作要做”C#Windows服务 - 本地计算机上的服务已启动,然后停止?
我相信一定有我的代码中的一些错误...
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。我已勾选'允许服务与桌面交互'
检查以确保您的服务运行的帐户可以访问这些文件(包括.wav和.mp3文件的写入访问权限)。
您的代码也可能导致未处理的异常。我不确定,但可能会在事件日志中看到。你也可以让你的服务将消息明确写出到事件日志中(就像例外情况一样);看看这个链接:http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
您没有为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
时发生的情况 - 应用程序刚刚退出。
+1是。学习如何编写Windows服务时,这是一个非常常见的绊脚石。 –
线程中的布尔标志也是如此。使用一个AutoResetEvent。 –
更新了更合适的'CancellationTokenSource'。 'AutoResetEvent'太旧了= D – Tejs
打开eventvwr.msc。在那里你会看到关于为什么你的Windows服务停止工作的异常细节。顺便说一句,你应该尽快离开OnStart方法,因为你只有 有30秒完成OnStart方法。 关于MSDN有一篇很好的文章,描述了“如何调试”Windows服务。
查看Windows事件日志。它可能有一些关于你的代码轰炸未处理的异常。 –