1

我正在使用 SharpSSH 将命令从 Windows 窗体发送到一台 linux 机器。一切都按预期工作,只是我无法实时更新输出。命令执行完成后会出现输出。如何在输出发生时更新输出。

这是我作为后台工作者运行的代码。

private void execute_green_DoWork(object sender, DoWorkEventArgs e)
        {
            List<object> argumentList = e.Argument as List<object>;
            string isp_username = (string)argumentList[0];
            string isp_password = (string)argumentList[1];
            string ssid = (string)argumentList[2];

            string stdOut = null;
            string stdError = null;
            string address = "192.168.1.100";
            string start = "Connecting...";
            this.Invoke(new MethodInvoker(delegate { progressWindow.green_update(start); }));
            System.Threading.Thread.Sleep(200);
            string user = "user";
            string pass = "password";
            string status = "Connected.....";
            this.Invoke(new MethodInvoker(delegate { progressWindow.green_update(status); }));
            System.Threading.Thread.Sleep(200);
            this.Invoke(new MethodInvoker(delegate { progressWindow.green_update("Programming....."); }));
            SshExec ssh_green = new SshExec(address, user, pass);
            ssh_green.Connect();
            ssh_green.RunCommand("cfg_green " + isp_username + " " + isp_password + " " + ssid, ref stdOut, ref stdError);
            output_green = stdOut;
            ssh_green.Close();

在上面的 output_green 被渲染到richtextbox。有SharpSSH知识的人,请您指导我。

4

1 回答 1

1

这是使用同步上下文来更新 Form 的 lblTimer 标签:

CS:

public partial class MainForm : Form
{
    private readonly SynchronizationContext _context;

    public MainForm()
    {
        InitializeComponent();
        // the context of MainForm, main UI thread
        // 1 Application has 1 main UI thread
        _context = SynchronizationContext.Current;
    }

    private void BtnRunAnotherThreadClick(object sender, EventArgs e)
    {
        Task.Run(() =>
                 {
                     while (true)
                     {
                         Thread.Sleep(1000);
                         //lblTimer.Text = DateTime.Now.ToLongTimeString(); // no work
                         UpdateTimerInMainThread(); // work
                     }
                 });
    }

    private void UpdateTimerInMainThread()
    {
        //SynchronizationContext.Current, here, is context of running thread (Task)
        _context.Post(SetTimer, DateTime.Now.ToLongTimeString());
    }

    public void SetTimer(object content)
    {
        lblTimer.Text = (string)content;
    }
}

在此处输入图像描述

希望这有帮助。

于 2015-06-30T14:48:47.600 回答