Windows服务的简短示例以及如何安装和运行它?
我在互联网上搜索过,但我尝试过的东西上没有任何关于On Start方法的内容。另外,当我尝试安装它时,错误OpenSCManager
会不断弹出。
答案 0 :(得分:3)
在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
然后运行InstallUtil.exe "c:\myservice.exe"
转到services.msc
,然后找到并启动您的服务
答案 1 :(得分:2)
以下是有关如何在C#中编写和安装Windows服务的一些示例:
答案 2 :(得分:0)
我对这个问题的回答为您提供了在C#中创建Windows服务的分步说明。
我对此问题的回答显示您必须修改服务,以便它可以从命令行安装和卸载。
自1.1以来,InstallUtil.exe已成为.NET的一部分,因此它应该在您的系统上。但是,您可能无法从“正常”命令提示符中使用它。如果安装了Visual Studio,请打开Visual Studio命令提示符。这将定义适当的环境变量,使得InstallUtil可以在没有路径信息的情况下访问。
OnStart()
回调使您有机会启动服务的业务逻辑。如果您在OnStart()
回调中未执行任何操作,您的服务将立即关闭。通常,您将启动一个执行您感兴趣的工作的线程。这是一个小例子,向您展示它的外观。
private static System.Timers.Timer _timer;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Write a message to the event log.
string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime);
EventLog.WriteEntry(msg, EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
// Create a timer with a 10-econd interval.
_timer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Signal the timer to raise Elapsed events every 10 seconds.
_timer.Start();
}
protected override void OnStop()
{
// Stop and dispose of the timer.
_timer.Stop();
_timer.Dispose();
}
执行此类操作可有效保持服务正常运行,直至其关闭。希望这可以帮助。