Search code examples
c#asynchronouseventsprocessstartinfo

ProcessStartInfo and event / async with parameter


I have an href list and I run the command it looks up at this location (svn) asynchronously. In ProcessOnErrorDataReceived I have to add s + outLine to the list. I do not know how to do this. It is possible to send s to an event or I need to call a method synchronously.

Search(List<string> path) {
 foreach(var s in path){
   ...
   if (process.StartInfo.RedirectStandardOutput)
                process.OutputDataReceived += ProcessOnErrorDataReceived;
    }
  }

  private void ProcessOnErrorDataReceived(object sendingProcess,
                                  DataReceivedEventArgs outLine)
    {
        Process p = sendingProcess as Process;
        if (outLine.Data != null)
            list.Add(outLine.Data);  //Here +s
    }

Solution

  • Try something like this. Here we create a closure and capture the locS value. So, when the even occurs, we can pass captured value to the ProcessOnErrorDataReceived

    Search(List<string> path)
    {
      foreach(var s in path)
      {
        ...
        if (process.StartInfo.RedirectStandardOutput)
        {
          var locS = s;
          process.OutputDataReceived += (sender,e) =>
             ProcessOnErrorDataReceived(sender, e, locS);
        }
      }
    }
    
    private void ProcessOnErrorDataReceived(object sendingProcess,
      DataReceivedEventArgs outLine, string s)
    {
      Process p = sendingProcess as Process;
      if (outLine.Data != null)
          list.Add(outLine.Data + s);  //Here +s
    }