2010-11-09 105 views
1

我有一个方法可以创建一个调用控制台应用程序的进程。将捕获的数据从OutputDataReceived发回给调用者

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?我不能使用单例,因为这个过程将在多个线程中执行。

回答

6

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

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

(?还有,应该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; 
    } 
+0

谢谢!我想有人会告诉我,没有解决方案。继承人什么我添加process.OutputDataReceived + =(sender,e)=> results = Convert.ToDouble(e.Data);我应该删除process.OutputDataReceived + =新的DataReceivedEventHandler(process_OutputDataReceived); 。但我在做什么静态无效process_OutputDataReceived(对象发件人,DataReceivedEventArgs e)? – 2010-11-10 03:35:22

+0

我认为存在一些误解(无论如何我的错)。结果不是简单的控制台输出。有多行控制台输出。加上我需要做一些过滤之前,我得到的结果。可能吗?谢谢。 – 2010-11-10 03:50:27

+0

您可以删除旧的'process_OutputDataReceived'。查看我的编辑,了解如何在处理程序中执行多个任务。 – 2010-11-10 08:09:59

相关问题