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

Sya*_*hya 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*son 6

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

process.OutputDataReceived += (sender, e) => results = e.Data;
Run Code Online (Sandbox Code Playgroud)

(另外,应该resultsstringdouble?)

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

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;
   }
Run Code Online (Sandbox Code Playgroud)