C#通过Process.Exited发送参数

时间:2013-07-12 18:26:23

标签: c#

我启动了一个使用process.exited发送程序指令的流程,该流程已完成。

它工作正常,但我需要向Process_Exited()方法发送一个参数。像这样:

process.exited += Process_Exited(jobnumber);

但这不起作用。这是我的代码:

public void x264_thread(string jobnumber, string x264_argument, string audio_argument)
{
    file = new System.IO.StreamWriter("c:\\output\\current.out");
    mysqlconnect("UPDATE h264_encoder set status = 'running' where jobnumber = '" + jobnumber + "'");
    var proc = new Process();
    proc.StartInfo.FileName = "C:\\ffmbc\\ffmbc.exe";
    proc.StartInfo.Arguments = x264_argument;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;
    proc.EnableRaisingEvents = true;
    proc.StartInfo.CreateNoWindow = true;
    proc.ErrorDataReceived += proc_DataReceived;
    proc.OutputDataReceived += proc_DataReceived;
    proc.Exited += process_Exited(JobNumber); //This is where I would like to include a argument

    proc.Start();
    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();
}

然后转到process_Exited方法:

public void process_Exited(object sender, EventArgs e, string JobNumber) //This does not work. It does not pass the string JobNumber
{
    //Do Stuff
}

我想从{x264_thread

发送process_Exited()方法参数

2 个答案:

答案 0 :(得分:7)

只需使用lambda:

proc.Exited += (sender, e) => process_Exited(sender, e, JobNumber);

编译器现在生成大量IL,隐藏类和隐藏方法,使其全部工作。

Lambda非常适合修改签名和传递其他状态。

答案 1 :(得分:3)

您无法更改Process.Exited等事件处理程序的签名,但在事件处理程序代码中,您可以将sender转换为Process类型,因为sender实际上是public void process_Exited(object sender, EventArgs e) { Process myProcess = (Process)sender; // use myProcess to determine which job number.... // DoWork } 原始进程的实例。现在您已了解该过程,您可以确定您的JobNumber:

private Dictionary<Process, string> _processDictionary = 
                               new Dictionary<Process,string>();

现在,要获取哪个作业编号与哪个进程相关联,您可以执行以下操作:

在你的班级中添加一个字段:

x264_thread

_processDictionary.Add(proc, jobnumber); 方法中,您可以在创建流程后添加条目:

public void process_Exited(object sender, EventArgs e) 
{
    Process myProcess = (Process)sender;
    // use myProcess to determine which job number....
    var jobNumber = _processDictionary[myProcess];
    _processDictionary.Remove(myProcess);
    // DoWork
}

然后在您的事件处理程序中,您可以检索值:

{{1}}