我目前的工作在其上使用System.Diagnostic.Process方法来配置文件中启动了几个脚本的C#项目。确定哪个线程触发一个事件
我有一个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
}
感谢您提供任何帮助。
'startProductProcess_OutputDataReceived'将被调用从CLR ThreadPool的Thread中,不是你的,所以它们不会有“名称”。然而,'sender'是你正在做IO的'Process' - 也许你可以用它来回到你的产品名称。 – 2012-04-20 10:08:39
发布的代码还在主线程上运行'startProducts()',打字错误? – 2012-04-20 10:12:09
@亨克霍尔特曼是的,抱歉,这是一个错字 – Boardy 2012-04-20 10:28:17