我想启动刚刚安装的Windows服务.
ServiceBase[] ServicesToRun;
if (bool.Parse(System.Configuration.ConfigurationManager.AppSettings["RunService"]))
{
ServicesToRun = new ServiceBase[] { new IvrService() };
ServiceBase.Run(ServicesToRun);
}
Run Code Online (Sandbox Code Playgroud)
IvrService代码是:
partial class IvrService : ServiceBase
{
public IvrService()
{
InitializeComponent();
Process myProcess;
myProcess = System.Diagnostics.Process.GetCurrentProcess();
string pathname = Path.GetDirectoryName(myProcess.MainModule.FileName);
//eventLog1.WriteEntry(pathname);
Directory.SetCurrentDirectory(pathname);
}
protected override void OnStart(string[] args)
{
string sProcessName = Process.GetCurrentProcess().ProcessName;
if (Environment.UserInteractive)
{
if (sProcessName.ToLower() != "services.exe")
{
// In an interactive session.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new IvrInteractive());
IvrApplication.Start(); // the key function of the service, start it here
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何启动该服务.使用ServiceController.Start()?但我已经有了ServiceBase.Run(ServicesToRun);它是否可以启动服务?
代码提示绝对值得赞赏.
要回答有关从代码启动服务的问题,您可能需要这样的东西(这相当于net start myservice从命令行运行):
ServiceController sc = new ServiceController();
sc.ServiceName = "myservice";
if (sc.Status == ServiceControllerStatus.Running ||
sc.Status == ServiceControllerStatus.StartPending)
{
Console.WriteLine("Service is already running");
}
else
{
try
{
Console.Write("Start pending... ");
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
if (sc.Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Service started successfully.");
}
else
{
Console.WriteLine("Service not started.");
Console.WriteLine(" Current State: {0}", sc.Status.ToString("f"));
}
}
catch (InvalidOperationException)
{
Console.WriteLine("Could not start the service.");
}
}
Run Code Online (Sandbox Code Playgroud)
这将启动服务,但请记住,它将与执行上述代码的进程不同.
现在回答有关调试服务的问题.
编辑:添加事件的样本流(基于一些评论的问题)
ServiceBase.Run在C#中或StartServiceCtrlDispatcher在本机代码中).然后开始运行其代码(将调用您的ServiceBase.OnStart()方法).ServiceBase.OnStop()方法.
编辑:允许服务作为普通可执行文件或命令行应用程序运行:一种方法是将您的应用程序配置为控制台应用程序,然后根据命令行开关运行不同的代码:
static void Main(string[] args)
{
if (args.Length == 0)
{
// we are running as a service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
}
else if (args[0].Equals("/debug", StringComparison.OrdinalIgnoreCase))
{
// run the code inline without it being a service
MyService debug = new MyService();
// use the debug object here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14717 次 |
| 最近记录: |