当前位置: 首页>>代码示例>>C#>>正文


C# ServiceProcess.ServiceController类代码示例

本文整理汇总了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;
            }
        }
开发者ID:OPCFoundation,项目名称:UA-.NET,代码行数:36,代码来源:ServiceManager.cs

示例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;
                }

            }
        }
开发者ID:kcsampson,项目名称:Kexplorer,代码行数:33,代码来源:AddMachineScript.cs

示例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++;
                        }
                    }

                }
            }
        }
开发者ID:damico,项目名称:open-audit,代码行数:27,代码来源:OpenAuditCheckService.cs

示例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
        }
开发者ID:psyCHOder,项目名称:conferencexp,代码行数:29,代码来源:RefServiceInstaller.cs

示例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);
        }
开发者ID:petarvucetin,项目名称:NServiceBus,代码行数:37,代码来源:ProcessUtil.cs

示例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;
            }
        }
开发者ID:NewAmbition,项目名称:ServiceNecromancer,代码行数:25,代码来源:Scrolls.cs

示例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();
 }
开发者ID:robertosiga,项目名称:windows-service-thread-install,代码行数:7,代码来源:ProjectInstaller.cs

示例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>();
        }
开发者ID:Falconne,项目名称:Emanate,代码行数:28,代码来源:MainWindowViewModel.cs

示例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;
        }
开发者ID:oriacle,项目名称:dropkick,代码行数:30,代码来源:WinServiceStopTask.cs

示例10: ServiceManager

        public ServiceManager(string serviceName)
        {
            _log = new FileLogger();

            _serviceController = new ServiceController();
            _serviceController.ServiceName = serviceName;
        }
开发者ID:electricneuron,项目名称:jonel.communicationservice,代码行数:7,代码来源:ServiceManager.cs

示例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;
        }
开发者ID:renyh1013,项目名称:dp2,代码行数:35,代码来源:InstallHelper.cs

示例12: MonitoredService

 internal MonitoredService(ServiceController service)
     : base()
 {
     _service = service;
     DisplayName = _service.DisplayName;
     IsValidService = true;
 }
开发者ID:scottoffen,项目名称:shazam,代码行数:7,代码来源:MonitoredService.cs

示例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();
                }
            }
        }
开发者ID:qdrive,项目名称:WindowsServiceTemplate,代码行数:60,代码来源:TheService.cs

示例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;
            }
        }
开发者ID:BillTheBest,项目名称:rhevUP,代码行数:32,代码来源:serviceOperations.cs

示例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;
            }
        }
开发者ID:BillTheBest,项目名称:rhevUP,代码行数:28,代码来源:serviceOperations.cs


注:本文中的System.ServiceProcess.ServiceController类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。