将捕获的数据从OutputDataReceived发送回调用方

时间:2010-11-09 08:46:39

标签: c# events

我有一个创建进程调用控制台应用程序的方法。

double myProcess()
{
    double results;

    Process process = new Process();
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
    process.StartInfo.FileName = filename;
    process.StartInfo.Arguments = argument;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.CreateNoWindow = true;
    process.Start(); 
    process.BeginOutputReadLine();
    process.WaitForExit();

    return results;
}

static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    string stringResults = (string)e.Data;
    .
    .
    do some work on stringResults...
    .
    .
    results = stringResults;
}

我的问题是,如何将process_OutputDataReceived中的数据发送回myProcess?我不能使用单例,因为有可能在多个线程中执行此过程。

1 个答案:

答案 0 :(得分:6)

OutputDataReceived处理程序不需要单独的方法;您可以使用匿名方法直接设置results变量:

process.OutputDataReceived += (sender, e) => results = e.Data;

(另外,results应该string还是double?)

编辑:当您需要在处理程序中执行更多工作时,有几种选择:

process.OutputDataReceived +=
   (sender, e) =>
   {
        string stringResults = e.Data;
        // do some work on stringResults...
        results = stringResults;
   }

// or

process.OutputDataReceived +=
   delegate(object sender, DataReceivedEventArgs e)
   {
        string stringResults = e.Data;
        // do some work on stringResults...
        results = stringResults;
   }