我的服务没有循环
本文关键字:循环 服务 我的 | 更新日期: 2023-09-27 18:23:48
这是我的第一个服务程序。如果我将此代码作为Console运行,LOOP会起作用,但如果我将其转换为服务,它最初会执行操作,但不会LOOP。你能帮我纠正一下吗?tnx
using System;
using System.Net;
using KICBservice;
using System.Data;
using ConsoleApplication1.Classes;
using System.IO;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;
namespace KICBService
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "KICB_Payment";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "KICB_Payment";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
class Program : ServiceBase
{
static void Main(string[] args)
{
ServiceBase.Run(new Program());
KICBservice.Service1SoapClient kicb = new KICBservice.Service1SoapClient();
kicb.ClientCredentials.Windows.ClientCredential = new NetworkCredential("register", "KICBregistr1");
kicb.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
while (true)
{
try
{
kicb.Open();
StreamWriter tw = File.AppendText("c:''KICB.log");
NewPayment np = new NewPayment();
np = kicb.GetPayment("register", "KICBregistr1");
// Operation with Database
tw.WriteLine("----------------");
tw.WriteLine(DateTime.Now);
tw.Close();
kicb.Close();
System.Threading.Thread.Sleep(60000);
}
catch (Exception ex)
{
kicb.Abort();
}
}
}
public Program()
{
this.ServiceName = "KICB_Payment";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
}
我正在粘贴程序的完整代码。
第一个代码位于哪里?
如果没有这个上下文,我的最佳猜测是,您的OnStart()方法会启动,然后该方法一结束,服务就会退出,因为没有什么可做的了
此外,我不喜欢while (true) { Sleep(60000); // do work }
服务模式。相反,您希望寻找一个实际阻止执行的函数来保持代码的运行。示例包括CCD_ 2和CCD_。如果你找不到这样的服务,你可能想做一些事情,比如设置一个预定的任务。
您已经将代码放置在函数之外。您在问题中显示的内容甚至不应该编译,而且它肯定不会循环。
注意OnStart
函数定义中的//TODO:
注释:
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}