【问题标题】:Logic for Windows Services & Getting UpdatesWindows 服务和获取更新的逻辑
【发布时间】:2012-11-29 03:18:49
【问题描述】:

我使用 vb.net 开发了一个 Windows 服务,它使用 OnStart Even...

  • 从 SQL 表中获取所有条目
  • 根据返回的行创建计划

它工作正常,安排他们的时间和东西。

问题:每当我必须向表中添加新行时,我必须重新启动服务,以便它可以抓取新创建的行。这给我带来了问题...可能有一个任务已经在运行,重新启动服务可能会破坏系统。

那么处理这个问题的最佳方法是什么?是否可以在不重新启动的情况下将新行加载到 Service 中?

谢谢

【问题讨论】:

  • 您可以标记条目,例如带有标志或添加行的日期/时间,并让服务定期检查新行。您可以使用表上的插入触发器通过服务代理为服务排队消息。这取决于您是否愿意拉取或推送新数据。
  • 但是如何....OnStart 事件一次性加载所有 ROWS。我无法使用新行再次触发 onStart 事件。我一定在这里遗漏了什么。
  • OnStart 将需要启动另一个工作线程。该线程将通过等待计时器定期检查数据库,或者将连接到队列并等待消息。该线程如何将任何新数据集成到您的计划中取决于您的应用程序。 OnStart 不应进行耗时的处理。它应该启动一个或多个工作线程,然后返回到服务控制器。
  • 如果可以为onStart事件搭建一个非常简单的基本代码结构就好了。
  • 有一个编码OnStart here的最小例子。

标签: c# vb.net winforms windows-services


【解决方案1】:

在数据库中使用轮询的概念。使用System.Threading.Timer 类,设置一些间隔,在此之后将调用 callback 方法,该方法将负责轮询数据库以获取新条目。

【讨论】:

  • 我的代码在 Windows 服务的 onStart 事件中......你是说我应该在 onStart 事件中继续汇集? onStart 事件在服务启动后运行,并将所有数据带入服务。
  • @FSX - Pooling 还是 polling?
  • @highwingers,是的,在 OnStart 中,您可以初始化计时器并启动它。稍后回调方法将定期调用(间隔由用户设置)。
  • @HABO,是的,也许是轮询。感谢指正,我的错我总是混淆。
【解决方案2】:

此 OnStart 由 Marc Gravell here 提供:

public void OnStart(string[] args) // should this be override?
{
    var worker = new Thread(DoWork);
    worker.Name = "MyWorker";
    worker.IsBackground = false;
    worker.Start();
}
void DoWork()
{
    // do long-running stuff
}

请注意,OnStart 可以启动多个线程,或者可以根据需要使用启动的第一个线程来启动其他线程。这允许您设置数据库轮询或在消息队列中等待数据的线程。


一个有用的提示:

Main 添加到您的服务允许您在 Visual Studio 中将其作为控制台应用程序运行。这大大简化了调试。

    static void Main(string[] args)
    {
        ServiceTemplate service = new ServiceTemplate();
        if (Environment.UserInteractive)
        {
            // The application is running from a console window, perhaps creating by Visual Studio.
            try
            {
                if (Console.WindowHeight < 10)
                    Console.WindowHeight = 10;
                if (Console.WindowWidth < 240) // Maximum supported width.
                    Console.WindowWidth = 240;
            }
            catch (Exception)
            {
                // We couldn't resize the console window.  So it goes.
            }

            service.OnStart(args);
            Console.Write("Press any key to stop program: ");
            Console.ReadKey();
            Console.Write("\r\nInvoking OnStop() ...");
            service.OnStop();

            Console.Write("Press any key to exit: ");
            Console.ReadKey();
        }
        else
        {
            // The application is running as a service.
            // Misnomer.  The following registers the services with the Service Control Manager (SCM).  It doesn't run anything.
            ServiceBase.Run(service);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2010-12-24
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    相关资源
    最近更新 更多