问题
I'm using the System.Diagnostics.Process class to execute a command line program.
I am using the OutputDataReceived method to redirect the output to my own method.
pr.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
pr.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
However, I have multiple Threads running multiple instances of this cmd program. What I want to do is to be able to identify which process instance the output data came from - ideally, a string containing a name. (Each process has it's own progress bar on a GUI. I create another event to pass the output to the GUI, thus, I need to know which process the data came from to update their progress bar).
I started to experiment with:
public override delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e, string processName);
Then I realised that I would have to override the OutputDataReceived method inside the Process class. Which in turn would mean I have to create a custom class that inherits System.Diagnostics.Process, and have a method that accepts a string argument so the OutputDataReceived event can pass the process instance name (string) to my overridden DataReceivedEventHandler.
The purpose of the question is to get some opinions on how to proceed. Does what I propose seem the right way to accomplish what I want? Or, is there a better way to do it?
回答1:
Can you not just use the sender object passed back and check which process it is running?
回答2:
Aside from the existing answers of using the sender, you could also use lambda expressions (or anonymous method) to make this simpler:
pr.OutputDataReceived += (sender, args) => HandleData(pr, args);
where HandleData would have a signature of
void HandleData(Process process, DataReceivedEventArgs e)
Anonymous functions are a very handy way of propagating information which is known locally at event subscription time to code which needs to handle the event.
回答3:
You can typecast the sender parameter to the Process object (pr in your code snippet)
来源:https://stackoverflow.com/questions/3994599/c-sharp-overriding-an-event-handler-adding-a-parameter