【问题标题】:C# Windows Service -- the service on local computer started and then stopped?C# Windows 服务——本地计算机上的服务启动然后停止?
【发布时间】:2011-08-18 18:14:01
【问题描述】:

我正在尝试创建我的第一个 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。我已经勾选了“允许服务与桌面交互”

【问题讨论】:

  • 查看 Windows 事件日志。它可能与您的代码轰炸未处理的异常有关。

标签: c# process windows-services


【解决方案1】:

您没有为 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 服务时非常常见的绊脚石。
  • 更新为更合适的CancellationTokenSourceAutoResetEvent 太老派了=D
【解决方案2】:

检查以确保运行您的服务的帐户可以访问这些文件(包括 .wav 和 .mp3 文件的写入权限)。

您的代码也可能导致未处理的异常。我不确定,但这可能在事件日志中可见。您还可以让您的服务将消息显式写入事件日志(例如在异常情况下);看看这个链接:http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

【讨论】:

    【解决方案3】:

    打开 eventvwr.msc。在那里,您将看到有关 Windows 服务停止工作的原因的异常详细信息。顺便说一句,您应该尽快离开 OnStart 方法,因为您只 有 30 秒的时间来完成 OnStart 方法。 MSDN 上有一篇很棒的文章描述了“如何调试”Windows 服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 2016-10-21
      • 2016-06-10
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      相关资源
      最近更新 更多