1

The method Process.BeginOutputReadLine() reads the output asynchronously on a thread other than the GUI's thread. I am trying to find a way to use async and await in my C# code.

     p = new Process();
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.CreateNoWindow = true;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.FileName = "mplayer.exe";
     p.StartInfo.Arguments = @"C:\movie.mp4";
     p.OutputDataReceived += P_OutputDataReceived;
     p.Start();

Is there any way to update using an async method in Process class?

svick
  • 236,525
  • 50
  • 385
  • 514
Poulad
  • 1,149
  • 1
  • 12
  • 22
  • Possible duplicate of [How to update the GUI from another thread in C#?](http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c) – DDave May 25 '16 at 04:56

1 Answers1

1

Not all asynchronous methods in .net can be immediately used with async and await. Over there years there have been different async patterns introduced into the framework. Different portions of the framework have been implemented using different patterns. Have a look here for a description of the different patterns: https://msdn.microsoft.com/en-us/library/jj152938(v=vs.110).aspx

In your case, the interface is implemented as an Event-based Asynchronous Pattern (EAP) since there is a event handler and a method to initiate.

There is a good article here: https://msdn.microsoft.com/en-us/library/hh873178(v=vs.110).aspx which discusses interop between the async patterns and discusses what you're looking for.

However, you don't need to get into that, you can just use p.StandardOutput.ReadAsync which is an awaitable method which will read the same output stream that OutputDataReceived will read.

CamW
  • 3,223
  • 24
  • 34
  • I don't think this is EAP. Just because there is an event doesn't mean it's EAP. – svick May 25 '16 at 12:54
  • @svick, I suppose that the semantics are debatable. You could ask the question, "Are you making an async call or asking that events start firing when data is received?" while it may not be EAP to the letter of the law, it does very closely resemble it. – CamW May 26 '16 at 05:02