【发布时间】:2018-07-23 08:23:20
【问题描述】:
我是 Windows 服务的新手,查找了很多示例和资料,还搜索了之前提出的问题,但我还没有找到解决问题的方法。 我正在用 c# 编写一个 Windows 服务,它将 SOAP 请求发送到服务器,组织接收到的数据并准备好将其存储到历史数据库中。
最初我将它设为控制台应用程序,但它需要在后台按计划运行。这就是我选择 Windows 服务的原因。作为一个控制台应用程序,该程序至少需要 20 分钟,但这可能需要一个多小时,具体取决于数据量。
Windows 服务在 30 秒后返回错误,代码为 1053:服务未及时响应启动或控制请求。 我认为这与服务试图在 onStart() 中运行整个代码有关,因此服务没有及时返回。
我正在使用以下设计:
myProgram.cs:
public MyService()
{
InitializeComponent();
ExecuteProgram();
}
protected override void OnStart(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 *24; // every 24h
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
ExecuteProgram();
}
protected override void OnStop()
{
}
public void ExecuteProgram()
{
//Here is the code for SOAP requests, preparing data and for making the
import file for the historian.
}
在 Program.cs 中:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
try
{
#if (DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
#else
if (Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
#endif
}
catch (Exception ex)
{
throw (ex);
}
}
}
希望你能帮我解决我的问题。
提前致谢!
科尔特
【问题讨论】:
-
scheduled tasks 会比 Windows 服务更合适吗?
-
@Phylogenesis:该程序只能在后台运行。我读到最好的应用程序类型是 Windows 服务,对吧?
-
您的代码预计每 24 小时运行一次;您只是将计划任务重新实现为 Windows 服务。如果您希望它只在后台运行,没有什么可以强迫您创建一个窗口,或者您可以将计划任务本身配置为在后台运行。
-
同意“这应该是一个计划任务”,它最终会让你的生活更轻松。
标签: c# windows-services