• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# ServiceProcess.ServiceController类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.ServiceProcess.ServiceController的典型用法代码示例。如果您正苦于以下问题:C# ServiceController类的具体用法?C# ServiceController怎么用?C# ServiceController使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ServiceController类属于System.ServiceProcess命名空间,在下文中一共展示了ServiceController类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: dbCopyButton_Click

        private void dbCopyButton_Click(object sender, EventArgs e)
        {
            if(dbNameTextBox.Text!= null && destFolderTextBox.Text!= null)
            {
                string filename;
                int index = dbNameTextBox.Text.LastIndexOf('\\');
                if(index != -1)
                    filename = dbNameTextBox.Text.Substring(index+1);
                else
                    filename = dbNameTextBox.Text;

                ServiceController service = new ServiceController("DpFamService");
                if (service.Status.Equals(ServiceControllerStatus.Running))
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                }

                try
                {
                    System.IO.File.Copy(dbNameTextBox.Text, destFolderTextBox.Text + "\\" + filename);
                    System.IO.File.Delete(dbNameTextBox.Text);

                    MessageBox.Show("Database Copied Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception exc)
                {
                    CLogger.WriteLog(ELogLevel.ERROR, "Error while copying file to " + destFolderTextBox.Text + " " + exc.Message);
                    MessageBox.Show("Could not Copy Database", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                service.Start();
            }
        }
开发者ID:tkhurana,项目名称:File-Access-Monitor,代码行数:33,代码来源:SettingsWindow.cs


示例17: btnConnect_Click

        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;

            // wcf client to the service
            IConsoleService pipeProxy = OpenChannelToService();

            pipeProxy.UpdateConfiguration("registrationCode", txtCode.Text);

            ServiceController sc = new ServiceController();
            sc.ServiceName = "Liberatio Agent";

            // stop the service, wait 2 seconds, then start it
            try
            {
                sc.Stop();
                var timeout = new TimeSpan(0, 0, 2); // 2 seconds
                sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                sc.Start();
            }
            catch (InvalidOperationException)
            {

            }

            this.Dispose(); // hide and dispose
        }
开发者ID:joshuasmartin,项目名称:liberatio-agent-windows,代码行数:27,代码来源:FormRegister.cs


示例18: ServiceControllerExecute

        private void ServiceControllerExecute(string serviceName)
        {
            ServiceQuery queryTask = new ServiceQuery();
            queryTask.BuildEngine = new MockBuild();
            queryTask.ServiceName = serviceName;
            Assert.IsTrue(queryTask.Execute(), "Execute query failed");

            ServiceController task = new ServiceController();
            task.BuildEngine = new MockBuild();
            task.ServiceName = serviceName;

            if (ServiceQuery.UNKNOWN_STATUS.Equals(queryTask.Status))
            {
                Assert.Ignore("Couldn't find the '{0}' service on '{1}'",
                        queryTask.ServiceName, queryTask.MachineName);
            }
            else if (ServiceControllerStatus.Stopped.ToString().Equals(queryTask.Status))
            {
                task.Action = "Start";
            }
            else if (ServiceControllerStatus.Running.ToString().Equals(queryTask.Status))
            {
                task.Action = "Restart";
            }
            else
            {
                Assert.Ignore("'{0}' service on '{1}' is '{2}'",
                    queryTask.ServiceName, queryTask.MachineName, queryTask.Status);
            }

            Assert.IsTrue(task.Execute(), "Execute Failed");
            Assert.IsNotNull(task.Status, "Status Null");
        }
开发者ID:trippleflux,项目名称:jezatools,代码行数:33,代码来源:ServiceControllerTest.cs


示例19: InstallService

 /// <summary>
 /// 安装服务:
 /// </summary>
 /// <param name="filepath"></param>
 public void InstallService(string filepath)
 {
     try
     {
         string serviceName = GetServiceName(filepath);
         ServiceController service = new ServiceController(serviceName);
         if (!ServiceIsExisted(serviceName))
         {
             //Install Service
             AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller() { UseNewContext = true, Path = filepath };
             myAssemblyInstaller.Install(new Hashtable());
             myAssemblyInstaller.Commit(new Hashtable());
             myAssemblyInstaller.Dispose();
             //--Start Service
             service.Start();
         }
         else
         {
             if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
             {
                 service.Start();
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception("installServiceError/n" + ex.Message);
     }
 }
开发者ID:yangdaichun,项目名称:ZHXY.ZSXT,代码行数:33,代码来源:ManageService.cs


示例20: Running

 /// <summary>
 /// Checks to see if the Mongo DB service is currently running.
 /// </summary>
 /// <returns>True if currently running, otherwise false.</returns>
 public static bool Running()
 {
     var service = new ServiceController(MongoServiceName);
     var result = (service.Status == ServiceControllerStatus.Running);
     service.Dispose();
     return result;
 }
开发者ID:moov2,项目名称:doberman,代码行数:11,代码来源:MongoService.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ServiceProcess.ServiceInstaller类代码示例发布时间:2022-05-26
下一篇:
C# ServiceProcess.ServiceBase类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap