我目前正在开发一个c#项目,该项目使用System.Diagnostic.Process方法在配置文件中启动几个脚本。
我有一个foreach循环,循环遍历每个脚本,它需要通过创建新线程,设置进程信息并启动进程并将该脚本的输出重定向到c#程序来启动。然后我使用Process.OutputDataReceived事件在程序接收输出时触发。
OutputDataReceived事件处理程序中是否有一种方法可以确定触发事件的线程的名称。
下面的代码创建线程并启动线程。
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();
}
线程启动后,调用此方法将触发输出事件
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();
}
输出事件如下所示,此事件需要确定线程的名称,以便它知道如何处理输出。
private void startProductProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
//Find thread name and perform event based on thread name
}
感谢您提供的任何帮助。
答案 0 :(得分:2)
由于在属于CLR ThreadPool但不属于您的线程的线程上调用IO回调,因此它们没有名称。因此,您希望将您的线程名称与您的进程相关联。
远非优雅,但我认为它有效:
在班级属性
中添加Dictionnary<Process, string> _processTags;
然后将startProducts
更改为:
private void startProducts(string startScript)
{
//Thread productThread = new Thread();
Process startProductProcess = new Process();
// Save tag
_processTags.Add(startProductProcess, Thread.CurrentThread.Name);
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();
}
startProductProcess_OutputDataReceived
:
private void startProductProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string threadName = _processTags[sender as Process];
// stuff...
}