如何更有效地从Shell控制台事件读取?

时间:2018-06-26 11:17:35

标签: c# shell console

一个简单的控制台代码,读取称为ShellStream的控制台,

private ShellStream Shell;

public TelnetConnection(string Hostname, int Port, string MySSHHost, string MySSHRootUser, string MySSHRootUserPassword)
       {   
               SshConnection(MySSHHost, MySSHRootUser, MySSHRootUserPassword);            
               shell.DataReceived += new EventHandler<ShellDataEventArgs>(shell_DataReceived);   /// Created a event

       }

因此,在下面创建了一个事件

private void shell_DataReceived( object sender, ShellDataEventArgs e)
       {
           ScbyteReceived = e.Data;
           string result = Encoding.UTF8.GetString(e.Data, 0, e.Data.Count());
           ConsoleRead = result; <---------------------here
           Console.WriteLine(result);
       }

现在我想实时读取事件,因此我创建了一个字符串变量“ ConsoleRead”并将“结果”传递给它

然后在另一个功能中,我开始从控制台读取内容,如下所示:

public string ReadWithTimeOut(int Tout)
   {
       long  mycount = 0;
       if (!sshClient.IsConnected) return null;
       StringBuilder sb = new StringBuilder();
       do
       {
           //ParseTelnet(sb);
           sb.Append(ConsoleRead);    /// <-----------------here
           System.Threading.Thread.Sleep(TimeOutMs);
           mycount += TimeOutMs;
       } while (mycount < (long) Tout);
       return sb.ToString();
   }

我知道这不是正确的方法。你们可以建议我一种更好的实时读取Shell控制台并将其传递给ReadWithTimeOut()方法的方法。注意我仅在需要时才调用ReadWithTimeOut方法。

1 个答案:

答案 0 :(得分:0)

好吧,这是我找到的解决方案,您需要做的就是使用Shell.read()而不是字符串“ ConsoleRead”。无需创建shell事件(以我为例)。 希望这对以后的人有所帮助。

 do
       {  
           //sb.Append(ConsoleRead);    /// <-----------------here
           sb.Append(shell.Read());    // use this instead to read directly, more efficient than previous method
           System.Threading.Thread.Sleep(TimeOutMs);
           mycount += TimeOutMs;
       } while (mycount < (long) Tout);
         return sb.ToString();