尝试启动/停止服务时进度条/圆圈

时间:2011-06-22 18:14:08

标签: c# winforms progress-bar backgroundworker

我有一个启动和停止服务的项目。 大多数时候它很快但有时却不是。所以我想告诉用户正在执行的功能,他应该等待而不是点击其他任何东西。

所以这是我的代码:

  public Form1()
    {
        InitializeComponent();
        this.MaximizeBox = false;
    }        

    private void StartService_button_Click(object sender, EventArgs e)
    {
        StartService("aspnet_state", 60000);           
    }

    private void StartService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);

        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }

    private void StopService_button_Click(object sender, EventArgs e)
    {
        StopService("aspnet_state", 60000);          
    }

    private void StopService(string serviceName, int timeoutMilliseconds)
    {
        //TBD:Remove_Try_Catch          
        ServiceController service = new ServiceController(serviceName);
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }

    private void RestartService_button_Click(object sender, EventArgs e)
    {
        RestartService("aspnet_state", 60000);          
    }

    private void RestartService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);

        int millisec1 = Environment.TickCount;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
        if (!(service.Status.Equals(ServiceControllerStatus.Stopped) || service.Status.Equals(ServiceControllerStatus.StopPending)))
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
        // count the rest of the timeout
        int millisec2 = Environment.TickCount;
        timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

        if (!(service.Status.Equals(ServiceControllerStatus.Running) || service.Status.Equals(ServiceControllerStatus.StartPending)))
        {
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
    }       

1 个答案:

答案 0 :(得分:3)

如何在service.Start()之前将光标更改为WaitCursor并在.Start()方法之后将其更改回来