我使用Timers.Timer创建一个Windows服务。 如果我运行控制台应用程序工作正常,但如果我更改设置为Windows应用程序,我评论所有控制台功能,计时器无法正常工作。使用Console.ReadLine();都好。但我不应该打开控制台。
protected override void OnStart(string[] args)
{
AutoLog = false;
SetTimer();
Console.ReadLine();//if remove this line dont works
}
SetTimer的()
private void SetTimer()
{
mytimer = new Timer();
mytimer.Interval = 2000;
mytimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
mytimer.Enabled = true;
}
OnTimedEvent()
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
mytimer.Enabled = false;
EventLog evento1 = new EventLog();
evento1.Source = "scPublicar";
evento1.Log = "Publicar";
evento1.WriteEntry("Publicación corriendo, OnTimedEvent");
mytimer.Enabled = true;
}
Program.cs Main()
static void Main(string[] args)
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[] { new Publicar() };
if (Environment.UserInteractive)
{
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
onStartMethod.Invoke(service, new object[] { new string[] { } });
}
}
else
ServiceBase.Run(servicesToRun);
}
感谢您的回答
答案 0 :(得分:1)
在Visual Studio中运行/调试代码时,Environment.UserInteractive
为true
,进程立即停止。此行为是设计使然,您不应该做某事让它等待(例如,呼叫Console.ReadLine()
)。
您需要将代码作为Windows服务(而不是控制台应用程序)运行,然后由服务控制管理器进行管理。这意味着您可以将其配置为在系统启动时自动启动并继续运行。您也可以通过Windows管理控制台(services.msc
)中的服务管理单元启动和停止它。但要实现这一点,首先需要安装您的服务。
请按照以下步骤操作:
Program.cs
文件中,然后删除Console.ReadLine()
语句services.msc
。您应该找到一个名为“Service1”的服务。右键单击它以启动它。参考文献: