本文整理汇总了C#中System.ServiceProcess.ServiceController类的典型用法代码示例。如果您正苦于以下问题:C# ServiceController类的具体用法?C# ServiceController怎么用?C# ServiceController使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServiceController类属于System.ServiceProcess命名空间,在下文中一共展示了ServiceController类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartService
/// <summary>
/// Start the service with the given name and wait until the status of the service is running.
/// If the service status is not running after the given timeout then the service is considered not started.
/// You can call this method after stop or pause the service in order to re-start it.
/// </summary>
/// <param name="serviceName">The name of the service</param>
/// <param name="timeout">The timeout.</param>
/// <returns>True if the service has been started. Otherwise, false.</returns>
public static bool StartService(string serviceName, TimeSpan timeout)
{
try
{
bool timeoutEnabled = (timeout.CompareTo(TimeSpan.Zero) > 0);
using (ServiceController c = new ServiceController(serviceName))
{
c.Refresh();
if (timeoutEnabled && c.Status == ServiceControllerStatus.Running)
return true;
if (!timeoutEnabled && (c.Status == ServiceControllerStatus.Running || c.Status == ServiceControllerStatus.StartPending || c.Status == ServiceControllerStatus.ContinuePending))
return true;
if (c.Status == ServiceControllerStatus.Paused || c.Status == ServiceControllerStatus.ContinuePending)
c.Continue();
else if (c.Status == ServiceControllerStatus.Stopped || c.Status == ServiceControllerStatus.StartPending)
c.Start();
if (timeoutEnabled)
c.WaitForStatus(ServiceControllerStatus.Running, timeout);
return true;
}
}
catch (Exception e)
{
Utils.Trace(e, "Unexpected error starting service {0}.", serviceName);
return false;
}
}
示例2: Run
public override void Run(ServiceController[] services, Form mainForm, DataGrid serviceGrid)
{
var addedMachine = QuickDialog2.DoQuickDialog("Add A Machine's Services", "Machine Name:",".","Pattern ^(Enable|EPX):","");
if (addedMachine != null)
{
MachineName = addedMachine[0];
this.SearchPattern = addedMachine[1];
try
{
DataGrid dgrid = serviceGrid;
this.addView = (DataView)dgrid.DataSource;
CurrencyManager bm = (CurrencyManager)dgrid.BindingContext[this.addView];
ArrayList arrSelectedRows = new ArrayList();
this.addView = (DataView)bm.List;
mainForm.Invoke(new InvokeDelegate(this.AddMachineInGUIThread));
serviceGrid.Refresh();
}
finally
{
addedMachine = null;
addView = null;
}
}
}
示例3: serviceStart
private static void serviceStart()
{
ServiceController[] scServices;
scServices = ServiceController.GetServices();
foreach (ServiceController scTemp in scServices)
{
if (scTemp.ServiceName == "open-audit-check-service")
{
ServiceController sc = new ServiceController("open-audit-check-service");
if (sc.Status == ServiceControllerStatus.Stopped)
{
int tries = 0;
sc.Start();
while (sc.Status == ServiceControllerStatus.Stopped && tries < 5)
{
Thread.Sleep(1000);
sc.Refresh();
tries++;
}
}
}
}
}
示例4: OnCommitted
protected override void OnCommitted(IDictionary savedState)
{
base.OnCommitted (savedState);
// Setting the "Allow Interact with Desktop" option for this service.
ConnectionOptions connOpt = new ConnectionOptions();
connOpt.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt);
mgmtScope.Connect();
ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'");
ManagementBaseObject inParam = wmiService.GetMethodParameters("Change");
inParam["DesktopInteract"] = true;
ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null);
#region Start the reflector service immediately
try
{
ServiceController sc = new ServiceController("ConferenceXP Reflector Service");
sc.Start();
}
catch (Exception ex)
{
// Don't except - that would cause a rollback. Instead, just tell the user.
RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText,
ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
}
#endregion
}
示例5: ChangeServiceStatus
/// <summary>
/// Checks the status of the given controller, and if it isn't the requested state,
/// performs the given action, and checks the state again.
/// </summary>
/// <param name="controller"></param>
/// <param name="status"></param>
/// <param name="changeStatus"></param>
public static void ChangeServiceStatus(ServiceController controller, ServiceControllerStatus status, Action changeStatus)
{
if (controller.Status == status)
{
Console.Out.WriteLine(controller.ServiceName + " status is good: " + Enum.GetName(typeof(ServiceControllerStatus), status));
return;
}
Console.Out.WriteLine((controller.ServiceName + " status is NOT " + Enum.GetName(typeof(ServiceControllerStatus), status) + ". Changing status..."));
try
{
changeStatus();
}
catch (Win32Exception exception)
{
ThrowUnableToChangeStatus(controller.ServiceName, status, exception);
}
catch (InvalidOperationException exception)
{
ThrowUnableToChangeStatus(controller.ServiceName, status, exception);
}
var timeout = TimeSpan.FromSeconds(3);
controller.WaitForStatus(status, timeout);
if (controller.Status == status)
Console.Out.WriteLine((controller.ServiceName + " status changed successfully."));
else
ThrowUnableToChangeStatus(controller.ServiceName, status);
}
示例6: StartService
public static string StartService(string servicename, string[] parameters = null)
{
ServiceController sc = new ServiceController(servicename);
if (sc.Status == ServiceControllerStatus.Running) return "Running";
try
{
if (parameters != null)
{
sc.Start(parameters);
}
else
{
sc.Start();
}
return CheckServiceCondition(servicename);
}
catch (Exception e)
{
//Service can't start because you don't have rights, or its locked by another proces or application
return e.Message;
}
}
示例7: Install
public static void Install()
{
string[] s = { Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Service.NAME + ".exe" };
ManagedInstallerClass.InstallHelper(s);
ServiceController sc = new ServiceController(Service.NAME);
sc.Start();
}
示例8: MainWindowViewModel
public MainWindowViewModel()
{
startCommand = new DelegateCommand(StartService, CanStartService);
stopCommand = new DelegateCommand(StopService, CanStopService);
restartCommand = new DelegateCommand(RestartService, CanStopService);
saveCommand = new DelegateCommand(SaveAndExit, CanFindServiceConfiguration);
applyCommand = new DelegateCommand(SaveConfiguration, CanFindServiceConfiguration);
cancelCommand = new DelegateCommand(OnCloseRequested);
statusUpdateWorker.DoWork += UpdateServiceStatus;
statusUpdateWorker.RunWorkerCompleted += DisplayNewStatus;
// TODO: Dynamically determine service name
service = new ServiceController("EmanateService");
try
{
Status = service.DisplayName + " service is installed";
serviceIsInstalled = true;
}
catch (Exception)
{
Status = "Service is not installed";
serviceIsInstalled = false;
}
pluginConfigurationStorer = new PluginConfigurationStorer();
ConfigurationInfos = new ObservableCollection<ConfigurationInfo>();
}
示例9: Execute
public override DeploymentResult Execute()
{
var result = new DeploymentResult();
if (ServiceExists())
{
using (var c = new ServiceController(ServiceName, MachineName))
{
Logging.Coarse("[svc] Stopping service '{0}'", ServiceName);
if (c.CanStop)
{
int pid = GetProcessId(ServiceName);
c.Stop();
c.WaitForStatus(ServiceControllerStatus.Stopped, 30.Seconds());
//WaitForProcessToDie(pid);
}
}
result.AddGood("Stopped Service '{0}'", ServiceName);
Logging.Coarse("[svc] Stopped service '{0}'", ServiceName);
}
else
{
result.AddAlert("Service '{0}' does not exist and could not be stopped", ServiceName);
Logging.Coarse("[svc] Service '{0}' does not exist.", ServiceName);
}
return result;
}
示例10: ServiceManager
public ServiceManager(string serviceName)
{
_log = new FileLogger();
_serviceController = new ServiceController();
_serviceController.ServiceName = serviceName;
}
示例11: StartService
public static int StartService(string strServiceName,
out string strError)
{
strError = "";
ServiceController service = new ServiceController(strServiceName);
try
{
TimeSpan timeout = TimeSpan.FromMinutes(2);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch (Exception ex)
{
if (GetNativeErrorCode(ex) == 1060)
{
strError = "服务不存在";
return -1;
}
else if (GetNativeErrorCode(ex) == 1056)
{
strError = "调用前已经启动了";
return 0;
}
else
{
strError = ExceptionUtil.GetAutoText(ex);
return -1;
}
}
return 1;
}
示例12: MonitoredService
internal MonitoredService(ServiceController service)
: base()
{
_service = service;
DisplayName = _service.DisplayName;
IsValidService = true;
}
示例13: ScheduleService
public void ScheduleService()
{
try
{
Schedular = new Timer(SchedularCallback);
var mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
LogIt.WriteToFile("{0}" + "Mode - " + mode);
//Set the Default Time.
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
//Get the Scheduled Time from AppSettings.
scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next day.
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
//Get the Interval in Minutes from AppSettings.
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
//Set the Scheduled Time by adding the Interval to Current Time.
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next Interval.
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
var schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
LogIt.WriteToFile("{0}" + "Next Run In - " + schedule);
//LogIt.WriteToFile("Simple Service scheduled to run in: " + schedule + " {0}");
//Get the difference in Minutes between the Scheduled and Current Time.
var dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
Schedular.Change(dueTime, Timeout.Infinite);
}
catch (Exception ex)
{
//LogIt.WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
LogIt.WriteToFile("{0}" + "Error - " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (var serviceController = new ServiceController(Config.ServiceName))
{
serviceController.Stop();
}
}
}
示例14: StopService
/* Stop Service method */
public void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
Console.WriteLine("Stopping service: " + serviceName);
switch (service.Status)
{
case ServiceControllerStatus.Running:
case ServiceControllerStatus.Paused:
case ServiceControllerStatus.StopPending:
case ServiceControllerStatus.StartPending:
try
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
Console.WriteLine("Status:" + serviceName + " stopped");
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return;
}
default:
Console.WriteLine("Status:" + serviceName + " already stopped");
return;
}
}
示例15: StartService
/* Start Service method */
public void StartService(string serviceName)
{
ServiceController service = new ServiceController(serviceName);
switch (service.Status)
{
case ServiceControllerStatus.Stopped:
try
{
/* FIX-ME:
* For some reason RHEV-M Service doesn't return Service Running when the service
* is started and running. For this reason, we cannot verify the service status
* with service.WaitForStatus */
service.Start();
Console.WriteLine("Starting service: " + serviceName);
return;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return;
}
default:
Console.WriteLine("Status:" + serviceName + " already started");
return;
}
}