0

I start a few processes and I want to know which process called the OutputHandler, but I can’t get any information about the sending process. When I try to read a property, it always throws a InvalidOperationException

void ExecString()
{
    using (Process process = new Process())
    {
        process.StartInfo.FileName = executeExe;
        process.StartInfo.Arguments = string.Format("{0}/{1}@{2} @{3}", parameter0, parameter1, parameter2, parameter3);
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;

        process.EnableRaisingEvents = true;
        process.OutputDataReceived += OutputHandler;

        process.Start();
        process.BeginOutputReadLine();
    }
}   

void OutputHandler(object sendingProcess, DataReceivedEventArgs output)
{
    try
    {
        OutputText = output.Data;
        var tmpProcess = (Process)sendingProcess;
        var testId = tmpProcess.Id; // Throw Exception
    }
    catch (InvalidOperationException e)
    {
        OutputText = e.Message;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Check the docs for the [Process.Id](https://msdn.microsoft.com/en-us/library/system.diagnostics.process.id(v=vs.110).aspx) property. This is a documented exception, thrown if there's no ID, either because it hasn't been set yet or because there's no process. Perhaps the path was wrong, or the argument resulted in an error? – Panagiotis Kanavos Aug 01 '18 at 09:13
  • After the process start I get a process id, in the output handler I get the data that I expect. Just the sendingProcess object has no expected information. – user2369332 Aug 01 '18 at 09:47
  • Add the argument you need to your OutputHandler method, like *Processs prc*. And a lambda expression to subscribe the event so you can pass the *process* variable. The *using* statement has to go, the process object need to stay alive until it terminates. https://stackoverflow.com/questions/8644253/pass-parameter-to-eventhandler – Hans Passant Aug 01 '18 at 10:14
  • Process currentProcess = Process.GetCurrentProcess(); string pid = Process.Id.ToString(); Could you try this and respond me please.@user2369332 – Waayd Aug 01 '18 at 11:21
  • I removed the using statement and now I can access the process information from the eventhandler. Thanks a lot guys. – user2369332 Aug 01 '18 at 11:34
  • i think also my solution would help you :) did you ever try it. you are welcome. @user2369332 – Waayd Aug 01 '18 at 11:39

1 Answers1

0

Could you try this, It may help you;

Process currentProcess = Process.GetCurrentProcess(); 
var pid = currentProcess.Id; 
Waayd
  • 365
  • 3
  • 14