【问题标题】:Use of console.readline()使用 console.readline()
【发布时间】:2015-07-21 18:50:23
【问题描述】:

现在我有一个 C# 应用程序,它使用计时器 24/7 运行,它会经过所有 30 秒并执行任何操作。

我想让这个应用程序成为 Windows 服务,在后台运行。但是服务立即崩溃..

我的代码:

public static System.Timers.Timer _timer = new System.Timers.Timer();

static void Main(string[] args)
{
      _timer.Interval = 30000;
      _timer.Elapsed += timerCallback;
      _timer.AutoReset = true;
      _timer.Start();
}
public static void timerCallback(Object sender, System.Timers.ElapsedEventArgs e)
{
      // Do anything..
}

还有错误:

Windows 无法在本地计算机上启动应用程序服务。

错误 1053:服务没有及时响应启动或控制请求

在 windows 事件查看器中出现了这条消息:

等待应用程序服务连接时超时(30000 毫秒)。

但错误出现的速度超过 30 秒?!

有运行该服务的解决方案吗? 谢谢

迈克尔

【问题讨论】:

  • 能否贴出崩溃时事件日志中记录的代码和堆栈跟踪?
  • 这个问题你看了吗:stackoverflow.com/questions/3736599/…
  • Windows 服务通常不设计为与桌面交互。与其使用Console.ReadLine() 来阻止服务停止,不如将其放入一个连续循环中,除非发生错误。
  • @AdrianThompsonPhillips 添加了我的代码和错误消息

标签: c# windows-services


【解决方案1】:

您可以使用Timer 在 Windows 服务中定期执行逻辑,

protected override void OnStart(string[] args)
{
  base.OnStart(args);

  Timer timer = new Timer();
  timer.Interval = 30*1000;
  timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
  timer.Enabled = true;
  timer.Start();
}

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
  //put logic here that needs to be executed for every 30sec
}

【讨论】:

  • 这正是我到目前为止所拥有的,但是服务在启动时失败
  • 为了更好地调试服务,请按照these 步骤操作。看看里面出了什么问题。
  • 我认为错误是我没有 OnStart 函数并且该类不是由 ServiceBase 派生的?
  • 您是如何创建您的 Windows 服务的?您应该从 Visual Studio 添加 Windows 服务(就像向项目添加类一样简单)。有一个项目叫windows service。
  • 该应用程序是一个控制台应用程序,现在我想将其转换为 Windows 服务。这可能吗?还是我必须重写整个程序?
猜你喜欢
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 2015-03-07
  • 2022-08-23
  • 1970-01-01
  • 2013-03-04
  • 2013-08-23
  • 1970-01-01
相关资源
最近更新 更多