如何将字符串从另一个线程传递到C#WinForms

时间:2017-01-27 14:53:03

标签: multithreading events

我的项目需要一些帮助。

我有一个main方法,它启动一个cmd进程并将输出重定向到事件处理程序。

private void RunBTN_Click(object sender, EventArgs e)
    {
        this.process.StartInfo.FileName = sMasterBATname;
        this.process.StartInfo.UseShellExecute = false;
        this.process.StartInfo.CreateNoWindow = true;
        this.process.StartInfo.RedirectStandardOutput = true;
        this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
        this.process.StartInfo.RedirectStandardInput = true;
        this.process.Start();
        this.process.BeginOutputReadLine();
    }

CMD进程运行多个exe文件,一切都会好,但是一些exe输出被重定向到文本文件(“>>”命令),因此我的事件不会处理。

public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
    {
       if (outLine.Data != null && !String.IsNullOrWhiteSpace(outLine.Data))
        {

          if (outLine.Data.Contains(">>"))
            {
                string[] commandLine = outLine.Data.Split('>');
                this.logFileFullPath = commandLine[1];
                this.logFileFullPath = this.logFileFullPath.Replace('"', ' ').Trim();
                string[] split = logFileFullPath.Split('\\');
                this.logFileName = split[6];
                this.path = split[0] + "\\" + split[1] + "\\" + split[2] + "\\" + split[3] + "\\" + split[4] + "\\" + split[5];

                BatchRun.LogMonitor(this.logFileName,this.path) //this class will run on different thread 

           else
           {
               //validate content of received data
           }
            }
        }
    }

上述两种方法都位于部分类中。

日志监视器将在单独的线程上运行,并将执行循环以检查文本/日志文件的任何更新,如下所示,基于Tail like program

public class Monitor
 {
     public LogMonitor(string LogName, string LogPath)
       {

          using (StreamReader reader = new StreamReader(new FileStream(LogName,
                 FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
           {
            //start at the end of the file
            long lastMaxOffset = reader.BaseStream.Length;

              while (true)
              {
                System.Threading.Thread.Sleep(100);

                //if the file size has not changed, idle
                if (reader.BaseStream.Length == lastMaxOffset)
                    continue;

                //seek to the last max offset
                reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

                //read out of the file until the EOF
                string line = "";
                while ((line = reader.ReadLine()) != null)
                    Console.WriteLine(line);

                //update the last max offset
                lastMaxOffset = reader.BaseStream.Position;
              }
           }
}

我的问题是,我不知道如何在每次将新行添加到日志之后传递一个行变量,从LogMonitor方法到StandardOutputHandler,这样我就能以相同的方式验证日志文件的内容并相应地采取行动。

如果有人可以使用我的代码并粘贴一个非常棒的答案。或者也许有人可以提出更好的方法来实现我的目标?

我只使用C#2个月,所以对evens等没有很好的了解......

0 个答案:

没有答案