I am currently working on a c# project which is using the System.Diagnostic.Process method to start up a couple of scripts within a config file.
I have a foreach loop which loops through each script that it needs to start by creating a new thread, setting up the process info and starting the process and redirect the output from that script into the c# program. I am then using the Process.OutputDataReceived event to trigger when the program receives output.
Is there a way in the OutputDataReceived event handler to determine the name of the thread that triggered the event.
The code below creates the threads and starts the thread up.
public void prepareProductStart()
{
foreach ( ConfigManagement.ProductSettings product in configManagement.productSettings )
{
worker = new Thread(() => startProducts(product.startScript));
worker.IsBackground = false;
worker.Name = product.productName;
worker.Start();
}
When the thread has started it calls this method which will trigger the output event
private void startProducts(string startScript)
{
//Thread productThread = new Thread();
Process startProductProcess = new Process();
startProductProcess.StartInfo.FileName = startScript;
startProductProcess.StartInfo.UseShellExecute = false;
startProductProcess.StartInfo.RedirectStandardOutput = true;
StringBuilder processOutput = new StringBuilder("");
startProductProcess.OutputDataReceived += new DataReceivedEventHandler(startProductProcess_OutputDataReceived);
startProductProcess.Start();
startProductProcess.BeginOutputReadLine();
}
The output event looks like below and this event needs to determine the name of the thread so it know what to do with the output.
private void startProductProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
//Find thread name and perform event based on thread name
}
Thanks for any help you can provide.
Since IO callbacks are called on Threads that belong to the CLR ThreadPool and not yours, they don’t have a name. So you want to associate your thread name to your process, in fact.
Far from elegant, but well, I guess it works:
Add a
Dictionnary<Process, string> _processTags;in your class’ attributesThen change
startProductsto:And
startProductProcess_OutputDataReceived: