-
Notifications
You must be signed in to change notification settings - Fork 0
/
WindowsServiceFacadeReal.cs
72 lines (65 loc) · 2.33 KB
/
WindowsServiceFacadeReal.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace CommandBasedComponents.Infrastructure
{
public class WindowsServiceFacadeReal : IWindowsServiceFacade
{
bool IWindowsServiceFacade.IsStarted(string name)
{
return GetService(name).Status == ServiceControllerStatus.Running;
}
bool IWindowsServiceFacade.IsStopped(string name)
{
return GetService(name).Status == ServiceControllerStatus.Stopped;
}
public bool Exists(string name)
{
return GetService(name) != null;
}
public Task<bool> Kill(string name)
{
return Task.Factory.StartNew(() =>
{
var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services");
if(key == null)
return true;
var controller = GetService(name);
key = key.OpenSubKey(controller.ServiceName);
if(key == null)
return true;
var imagePath = (string)key.GetValue("ImagePath", null);
// find process & kill
return true;
});
}
public Task<bool> Start(string name)
{
return Task.Factory.StartNew(() =>
{
var controller = GetService(name);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMinutes(10));
return controller.Status == ServiceControllerStatus.Running;
});
}
public Task<bool> Stop(string name)
{
return Task.Factory.StartNew(() =>
{
var controller = GetService(name);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMinutes(10));
return controller.Status == ServiceControllerStatus.Stopped;
});
}
static ServiceController GetService(string name)
{
return ServiceController
.GetServices()
.FirstOrDefault(s => s.ServiceName == name);
}
}
}