我正在使用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知识的人,请指导我。
答案 0 :(得分: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;
}
}
希望得到这个帮助。