我使用vb.net开发了一个Windows服务,它使用 OnStart 执行以下操作甚至......
它工作正常,安排他们的时间和东西。
问题:每当我必须向表格添加新行时,我必须重新启动服务,因此它可以抓取新创建的行。这给我带来了问题......可能有一个已经运行的任务,重启服务可能会破坏系统。
那么处理这个问题的最佳方法是什么?是否可以在不重启的情况下将新行加载到Service中?
由于
答案 0 :(得分:1)
将轮询的概念用于数据库。使用System.Threading.Timer
类,设置一段时间,之后将调用回调方法,并负责轮询数据库以获取新条目。
答案 1 :(得分:0)
这个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);
}
}