【问题标题】:C# Converting Console App to ServiceC# 将控制台应用程序转换为服务
【发布时间】:2013-10-17 22:26:38
【问题描述】:

我正在尝试将控制台应用程序转换为 Windows 服务。我试图让服务的 onstart 方法在我的类中调用一个方法,但我似乎无法让它工作。我不确定我这样做是否正确。我在服务中的哪个位置放置课程信息

protected override void OnStart(string[] args)
{
   EventLog.WriteEntry("my service started");
   Debugger.Launch();
   Program pgrm = new Program();
   pgrm.Run();
}

来自评论:

namespace MyService {
 static class serviceProgram {
  /// <summary> 
  /// The main entry point for the application. 
  /// </summary> 
  static void Main() {
   ServiceBase[] ServicesToRun;
   ServicesToRun = new ServiceBase[] {
    new Service1()
   };
   ServiceBase.Run(ServicesToRun);
  }
 }
}

【问题讨论】:

  • 您是否将项目类型从控制台应用程序更改为 Windows 应用程序?你打电话给ServiceBase.Run
  • 是的,我在我的解决方案中创建了一个新项目作为 Windows 服务。
  • namespace MyService { static class serviceProgram { /// /// 应用程序的主要入口点。 /// static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } } }

标签: c# service console onstart


【解决方案1】:

Windows 服务上的MSDN documentation 非常好,拥有您开始使用所需的一切。

您遇到的问题是由于您的 OnStart 实现,它只应该用于设置服务以便它准备好启动,该方法必须立即返回。通常你会在另一个线程或计时器中运行大部分代码。请参阅页面OnStart 进行确认。

编辑: 在不知道您的 Windows 服务会做什么的情况下,很难告诉您如何实现它,但假设您想在服务运行时每 10 秒运行一次方法:

public partial class Service1 : ServiceBase
{
    private System.Timers.Timer _timer; 

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
#if DEBUG
        System.Diagnostics.Debugger.Launch(); // This will automatically prompt to attach the debugger if you are in Debug configuration
#endif

        _timer = new System.Timers.Timer(10 * 1000); //10 seconds
        _timer.Elapsed += TimerOnElapsed;
        _timer.Start();
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        // Call to run off to a database or do some processing
    }

    protected override void OnStop()
    {
        _timer.Stop();
        _timer.Elapsed -= TimerOnElapsed;
    }
}

这里,OnStart 方法在设置计时器后立即返回,TimerOnElapsed 将在工作线程上运行。我还添加了对System.Diagnostics.Debugger.Launch(); 的调用,这将使调试更加容易。

如果您有其他要求,请编辑您的问题或发表评论。

【讨论】:

  • 那是我的问题,我不确定在 OnStart 实现中放什么。你是什​​么意思把大部分代码放在一个单独的线程或计时器上?如果不是从 OnStart 调用,该进程如何知道运行我的代码。提前感谢您的耐心等待,服务对我来说是全新的
  • @user2892443 用一个例子编辑了我的答案。
【解决方案2】:

帮自己一个大忙,使用 topshelf http://topshelf-project.com/ 来创建您的服务。没有什么比我看到的更容易了。他们的文档非常好,部署再简单不过了。 c:/service/service.exe 安装路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多