开发者

progress bar/circle when trying to start/stop service

开发者 https://www.devze.com 2023-03-14 14:30 出处:网络
I have a project which starts and stops a service. Most of the times it is fast but sometimes it is not. so i want to way to show the user that is function is being executed and he should wait and not

I have a project which starts and stops a service. Most of the times it is fast but sometimes it is not. so i want to way to show the user that is function is being executed and he should wait and not click anything else.

so here is my code:

  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);
        }
    }       


How about changing the cursor to WaitCursor before the service.Start() and changing it back after the .Start() method

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号