1

我目前正在处理 ac# 项目,该项目使用 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
    }

感谢您的任何帮助,您可以提供。

4

1 回答 1

2

由于 IO 回调是在属于 CLR ThreadPool 而不是您的线程上调用的,因此它们没有名称。因此,实际上,您希望将线程名称与您的进程相关联。

远非优雅,但很好,我想它有效:

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...
}
于 2012-04-20T10:22:05.577 回答