views:

44

answers:

3

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?

+5  A: 

Can you not just use the sender object passed back and check which process it is running?

ck
There's no information in the sender object to identify which process it is.
johnnyturbo3
Looking at the Process attributes. I could set the process name using the Process.StartInfo.Domain attribute. Probably not good programming practise as Domain is not supposed to be used like this, but it should work.
johnnyturbo3
+2  A: 

You can typecast the sender parameter to the Process object (pr in your code snippet)

Isak Savo
+1  A: 

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.

Jon Skeet