启动服务(通过GUI)会使前端无响应

本文关键字:前端 响应 服务 通过 GUI 启动 | 更新日期: 2023-09-27 18:26:18

不幸的是,我对C#编程非常陌生,从未使用过GUI编码,所以我可能遵循了非常糟糕的做法。这是我正在做的一个片段。

总体目标是从机器中提取状态,这样我就可以告诉前端服务是否已经启动,而无需实际远程处理到机器中。任何建议都会很有帮助!

很抱歉,代码剪切似乎不能很好地与我的命名空间和类调用配合使用。

namespace General
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Password = "password";
            options.Username = "username";
            InitializeComponent();
        }
    public void Start(string programname)
    {
        textBox.Text = "Starting";
        ServiceController svc = new ServiceController("service name", "remote desktop name");
        svc.Start();
        svc.WaitForStatus(ServiceControllerStatus.Running, timer1);
        if (svc.Status == ServiceContrllerStatus.Running)
        {
            textBox8.Text = "Success";
        }
        else
        {
        textBox8.Text = "Fail";
        }
    }
    private void button_Click(object sender, EventArgs e)
    {
        Start(button.Text);
    }
}
}

启动服务(通过GUI)会使前端无响应

试试这个。

Thread myThread = new Thread(() =>
        {
            ServiceController svc = new ServiceController("service name", "remote desktop name");
            svc.Start();
            svc.WaitForStatus(ServiceControllerStatus.Running, timer1);
            if (svc.Status == ServiceContrllerStatus.Running)
            {
                Dispatcher.Invoke(() =>
                { //This is required to acccess the Main UI Thread If you don't do this you will get and error
                    textBox8.Text = "Success";
                });
            }
            else
            {
                Dispatcher.Invoke(() =>
                {
                    textBox8.Text = "Fail";
                });
            }
        });
        myThread.Start();