【发布时间】:2011-09-26 06:22:58
【问题描述】:
正如我在其他几个问题中所述,我一直在使用new SSH .NET library 连接到 Unix 服务器并运行各种脚本和命令。好吧,我终于尝试使用它在实时日志文件上运行 Unix tail -f 并在 Winforms RichTextBox 中显示尾巴。
由于图书馆还没有完全完善,我想出的唯一有点像解决方案似乎缺乏......就像当你知道必须有更好的方法时你得到的感觉。我将连接/拖尾代码放在一个单独的线程中,以避免 UI 线程锁定。该线程支持取消请求(这将允许连接正常退出,这是确保 Unix 端进程被终止的唯一方法)。到目前为止,这是我的代码(为了记录,这似乎有效,我只是想知道这是否是正确的方法):
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(lineIP, userName, password);
string command = "cd /logs; tail -f " + BuildFileName() + " \r\n";
using (var ssh = new SshClient(connectionInfo))
{
ssh.Connect();
var output = new MemoryStream();
var shell = ssh.CreateShell(Encoding.ASCII, command, output, output);
shell.Start();
long positionLastWrite = 0;
while (!TestBackgroundWorker.CancellationPending) //checks for cancel request
{
output.Position = positionLastWrite;
var result = new StreamReader(output, Encoding.ASCII).ReadToEnd();
positionLastWrite = output.Position;
UpdateTextBox(result);
Thread.Sleep(1000);
}
shell.Stop();
e.Cancel = true;
}
UpdateTextBox() 函数是一种线程安全的方法,用于更新用于显示来自不同线程的尾部的 RichTextBox。 positionLastWrite 的东西是为了确保我不会丢失 Thread.Sleep(1000) 之间的任何数据。
现在我不确定 2 件事,首先是我感觉每次都可能会因为整个 MemoryStream 位置的变化而错过一些数据(由于我缺乏对 MemoryStreams 的经验,其次是整个睡眠 1 秒钟,然后再次更新,这件事似乎很陈旧而且效率低下......有什么想法吗?
【问题讨论】:
标签: c# multithreading unix .net-4.0 ssh