C# windows服务(带计时器)在没有控制台的情况下不工作
我用Timer.Timer创建了一个windows服务。 如果我作为控制台应用程序运行正常,但如果我将设置更改为windows应用程序并注释所有控制台功能,则计时器不工作。使用Console.ReadLine();一切都好。但我不应该打开控制台C# windows服务(带计时器)在没有控制台的情况下不工作,c#,.net,console,windows-services,system.timers.timer,C#,.net,Console,Windows Services,System.timers.timer,我用Timer.Timer创建了一个windows服务。 如果我作为控制台应用程序运行正常,但如果我将设置更改为windows应用程序并注释所有控制台功能,则计时器不工作。使用Console.ReadLine();一切都好。但我不应该打开控制台 protected override void OnStart(string[] args) { AutoLog = false; SetTimer(); Console.ReadLine();/
protected override void OnStart(string[] args)
{
AutoLog = false;
SetTimer();
Console.ReadLine();//if remove this line dont works
}
SetTimer()
OnTimedEvent()
Program.cs Main()
感谢您在Visual Studio中运行/调试代码时给出的答案,然后
环境。UserInteractive
为true
,过程立即停止。这种行为是出于设计,您不应该让它等待(例如,调用Console.ReadLine()
)
您需要将代码作为Windows服务(而不是控制台应用程序)运行,然后它将由服务控制管理器管理。这意味着您可以将其配置为在系统启动时自动启动并保持运行。您还可以通过Windows管理控制台中的服务管理单元(Services.msc
)启动和停止它。但要使其工作,您首先需要安装服务
遵循以下步骤:
Program.cs
文件中,并删除Console.ReadLine()
语句services.msc
。您应该找到一个名为“Service1”的服务。右键单击它以启动它环境。UserInteractive
为true
,该过程立即停止。这种行为是出于设计,您不应该让它等待(例如,调用Console.ReadLine()
)
您需要将代码作为Windows服务(而不是控制台应用程序)运行,然后它将由服务控制管理器管理。这意味着您可以将其配置为在系统启动时自动启动并保持运行。您还可以通过Windows管理控制台中的服务管理单元(Services.msc
)启动和停止它。但要使其工作,您首先需要安装服务
遵循以下步骤:
Program.cs
文件中,并删除Console.ReadLine()
语句services.msc
。您应该找到一个名为“Service1”的服务。右键单击它以启动它private void SetTimer()
{
mytimer = new Timer();
mytimer.Interval = 2000;
mytimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
mytimer.Enabled = true;
}
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;
}
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);
}