I'm using System.Diagnostics.Process class to convert wav file to mp3 file in a separated process. The method that does the job like this:
public void ConvertWavToMp3 (TempFile srcFile, string title, Action<TempFile, Exception> complete)
{
var argument_fmt = "-S --resample 16 --tt {0} --add-id3v2 {1} {2}";
var dstFile = new TempFile(Path.GetTempFileName());
var proc = new System.Diagnostics.Process ();
proc.EnableRaisingEvents = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "lame";
proc.StartInfo.Arguments = String.Format (argument_fmt,
title,
srcFile.Path,
dstFile.Path);
proc.Exited += delegate(object sender, EventArgs e) {
proc.WaitForExit();
srcFile.Delete();
complete(dstFile, null);
};
proc.Start();
}
I'm worried about GC because as proc is only a local variable, theoretically it doesn't exist anymore when the method returns. Therefor, proc can be garbage collected and the callback function complete will never be called.
But I don't really want to record proc somewhere and dispose it after the process exits, as that would expose the internal mechanism of how the wav to mp3 conversion is implemented.
Is my concern about GC valid? If GC of is potential problem, is there any way that I could prevent it without having to return the proc in this method?
BTW, I'm using Mono on linux.
Edit
Thanks for replies. I'm confirmed that I need to keep a copy of the process. So here's what I did:
public class LameConverter : IAudioConverter
{
// We need to store a reference to the process in case it was GCed.
IList<Process> _ProcList = new List<Process>();
public void ConvertWavToMp3 (TempFile srcFile, string title, Action<TempFile, Exception> complete)
{
// .. skipped ..
proc.Exited += delegate(object sender, EventArgs e) {
lock (this) {
_ProcList.Remove(proc);
}
proc.Dispose();
srcFile.Delete();
complete(dstFile, null);
};
proc.Start();
lock (this) {
_ProcList.Add(proc);
}
}
}
As long as the caller holds a reference to LameConverter, I don't need to worry about the GC anymore.
Any object without a root in the application is a candidate for garbage collection. In order to ensure that your callback fires you will need to find some place to store a reference to proc otherwise you will have undefined behavior.
One option in your case would be to return an object that encapsulates proc without exposing it via the public interface. Unfortunately in your case you must leak a bit of the underlying implementation to the caller of ConvertWavToMp3 in order to ensure that the desired behavior occurs.
Here's an alternate code sample that will work. However, it will block the call to ConvertWavToMp3(...) while the process is executing. Probably not what you want.
public void ConvertWavToMp3 (TempFile srcFile, string title, Action<TempFile, Exception> complete)
{
var argument_fmt = "-S --resample 16 --tt {0} --add-id3v2 {1} {2}";
var dstFile = new TempFile(Path.GetTempFileName());
var proc = new System.Diagnostics.Process ();
proc.EnableRaisingEvents = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "lame";
proc.StartInfo.Arguments = String.Format (argument_fmt,
title,
srcFile.Path,
dstFile.Path);
using(var wh = new System.Threading.ManualResetEvent(false))
{
proc.Exited += delegate(object sender, EventArgs e) {
proc.WaitForExit();
srcFile.Delete();
complete(dstFile, null);
wh.Set();
};
proc.Start();
wh.WaitOne();
}
}
Like I said, this is probably not what you want, unless you're in, say, a console app. If you're in a GUI app, keep a reference to your proc. Something like:
public class MyForm : Form
{
// other form stuff
private System.Diagnostics.Process _encoderProc;
private void doEncode_Click(object sender, EventArgs e)
{
var argument_fmt = "-S --resample 16 --tt {0} --add-id3v2 {1} {2}";
var dstFile = new TempFile(Path.GetTempFileName());
var proc = new System.Diagnostics.Process ();
proc.EnableRaisingEvents = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "lame";
proc.StartInfo.Arguments = String.Format (argument_fmt,
title,
srcFile.Path,
dstFile.Path);
proc.Exited += delegate(object sender, EventArgs e) {
proc.WaitForExit();
srcFile.Delete();
this.BeginInvoke((MethodInvoker)delegate {
// INSERT CODE HERE: your UI-related stuff that you want to do with dstFile
this._encoderProc = null;
});
};
proc.Start();
this._encoderProc = proc;
}
}
Note the use of BeginInvoke(...). If you're going to do UI-related stuff, it needs to be on the UI thread, and that Exited event won't fire on the UI thread. Hopefully this gets you moving in the right direction.
Related
i'm trying to open a process with c# and react to it, when it's been closed. This work's for me:
private void StartProc()
{
var process = new System.Diagnostics.Process { StartInfo = { FileName = "PathTo.exe" } };
process.Start();
process.EnableRaisingEvents = true;
process.Exited += this.Editor_Exited;
}
private void Editor_Exited(object sender, EventArgs e)
{
MessageBox.Show("Process canceled");
}
Lets say I'm opening a text editor with this code. If there is already an instance of this text editor the code won't open a second instance and also jumps instant in the Editor_Exited Code.
I want the code to open a new instance and don't jump in the Editor_Exited code.
string processName = "PathTo.exe";
var process = new System.Diagnostics.Process { StartInfo = { FileName = processName } };
if (process.Start())
{
process.EnableRaisingEvents = true;
process.Exited += this.Editor_Exited;
}
else
{
var p = Process.GetProcessesByName(processName);
p.WaitForExit();
}
I get this is not 100% what you are asking for, but its a work around
I am a newbie and trying to learn the right way.
Is it acceptable to use a Thread within a constructor to avoid gui(Form) to freeze when an object is created? I will reuse this class often.
class Cmd
{
protected static string parameters;
protected HashSet<string> list_result;
public Cmd( string parameters)
{
Thread Thread1 = new Thread(new ThreadStart(Process1));
Thread1.Start();
Thread1.Join();
}
private void Process1()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c " + parameters);
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
list_result = new HashSet<string>();
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
list_result.Add(line);
}
}
You don't even need a thread for this. You can use the StreamReader's asynchronous methods to read the input lines asynchronously:
private async void button1_Click(object sender, EventArgs e)
{
var lines=await Process1(#"dir g:\ /s");
var result= String.Join("|", lines);
this.textBox1.Text = result;
}
private async Task<HashSet<String>> Process1(string parameters)
{
var list_result = new HashSet<string>();
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c " + parameters);
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
while (!process.StandardOutput.EndOfStream)
{
string line = await process.StandardOutput.ReadLineAsync();
list_result.Add(line);
}
return list_result;
}
The advantage is that you don't waste a thread, you don't need any synchronization code or static fields to pass the parameters and read the results.
If you would like to avoid freeze in your UI when doing a time-consuming task, you should add BackgroundWorker to your form and run your task in its event handler
You can find the example here: https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx
You should also consider using newer async/await logic which is usually better than BackgroundWorker, as Panagiotis Kanavos mentioned in his answer
I'm learning C# and I'm creating a simple WinForms application, and what it does is starting a simple OpenVPN client:
void button_Connect_Click(object sender, EventArgs e)
{
var proc = new Process();
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = #"C:\Program Files (x86)\OpenVPN\bin";
proc.StartInfo.Arguments = "/c openvpn.exe --config config.ovpn --auto-proxy";
// set up output redirection
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
// Input
proc.StartInfo.RedirectStandardInput = true;
// Other
proc.EnableRaisingEvents = true;
proc.StartInfo.CreateNoWindow = false;
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
StreamWriter myStreamWriter = proc.StandardInput;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
if (e.Data != null)
{
string Data = e.Data.ToString();
if (Data.Contains("Enter Auth Username"))
{
myStreamWriter("myusername");
}
//MessageBox.Show(Data);
}
}
What it does now, is send all the output of the CMD to my program, which run commands depending on the output.
My current issue is, I need to write to the stream. I use myStreamWriter in proc_DataReceived, however it's not in the same context so it doesn't work.
I get the following error: The name 'myStreamWriter' does not exist in the current context, which is obviously non existent in that scope.
How do I make this work? Get/set properties? Like I said I'm quite new to C# so any help is appreciated.
In your form, add this field:
public class Form1Whatevver: Form {
private StreamWriter myStreamWriter;
}
Then in your code:
proc.Start();
this.myStreamWriter = proc.StandardInput;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
Now, myStreamWriter will be available to proc_DataReceived()
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
if (e.Data != null)
{
string Data = e.Data.ToString();
if (Data.Contains("Enter Auth Username"))
{
if (myStreamWriter != null) // Just in case
{
myStreamWriter("myusername");
}
}
//MessageBox.Show(Data);
}
}
The simple quick-fix is to define myStreamWriter as a field in the class (i.e. outside the scopes of your methods), then instantiate it from within one of the scopes:
private StreamWriter _myStreamWriter;
void button_Connect_Click(object sender, EventArgs e)
{
// Do some stuff
_myStreamWriter = proc.StandardInput;
// Do some stuff
}
Having done that should let you use it wherever you want within the class.
The concept you are talking about is Scope not context.
The are several ways you could alter your code so that you can access myStreamWriter from proc_DataReceived.
Arguably the simplest, is to pass the object you wish to effect as a parameter to the function. This is often a good approach in the perspective of future multi-threading and a drive towards a functional style.
void proc_DataReceived(
object sender,
DataReceivedEventArgs e,
StreamWriter writer)
{
...
writer("myusername");
...
}
However proc_DataReceived is obviously an event handler and you probably don't want to change the signature of the function.
If you declare myStreamWriter as a Private Member Variable at the class level you will be able to access from anywhere within the class. The this is optional but good form.
class YourForm : Form
{
private StreamWriter myStreamWriter;
void button_Connect_Click(...
{
...
this.myStreamWriter = proc.StandardInput;
...
}
void proc_DataRecieved(...
{
...
this.myStreamWriter("myusername");
...
}
}
A property implementation is not necessary unless you want to access the StreamWriter from outside the class/form.
For instance, a thread that is a BackgroundWorker, can be cast like:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
System.ComponentModel.BackgroundWorker senderWorker
= sender as System.ComponentModel.BackgroundWorker;
}
The code above represents what I have for my Background worker thread. I cast [sender] as a BackGround Worker - because I know thats what he is.
I can't seem to find what I should cast it to if: instead of a Background worker, what if I had used a Process class, and executed say a DOS batch file, using:
enter code here
Process proc = new Process();
proc.FileName = "some_dos_batch_file.bat";
proc.Exited = ProcessExited;
proc.Start();
Sorry about syntax, but when this process completes, its completion will be handled by 'ProcessExited' below. But What should I cast the sender arg to in THAT case - NOT a Background Worker obviously, but I'm not sure to what? I would like to use the .Results property the same as I did for the Background worker.
Thanks - sorry for the confusion.
enter code here
void ProcessExited(object sender, EventArgs e)
{
}
I hope I have understood your question, if not, please clarify. If you are talking about threading and using the System.Diagnostics.Process then you would need to use Thread events...consider this below a simple class called TestARP that shells out to the command line using a hidden window to retrieve the MAC/IP address of the active connection, with the output of the command redirected to a stream which is appended to a stringbuilder instance:
public class TestARP
{
private StringBuilder sbRedirectedOutput = new StringBuilder();
public string OutputData
{
get { return this.sbRedirectedOutput.ToString(); }
}
public void Run()
{
System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
ps.FileName = "arp";
ps.ErrorDialog = false;
ps.Arguments = "-a";
ps.CreateNoWindow = true;
ps.UseShellExecute = false;
ps.RedirectStandardOutput = true;
ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = ps;
proc.Exited += new EventHandler(proc_Exited);
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.WaitForExit();
proc.BeginOutputReadLine();
while (!proc.HasExited) ;
}
}
void proc_Exited(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("proc_Exited: Process Ended");
}
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (e.Data != null) this.sbRedirectedOutput.Append(e.Data + Environment.NewLine);
//System.Diagnostics.Debug.WriteLine("proc_OutputDataReceived: Data: " + e.Data);
}
}
If you were to run this in a thread the Process's events will still get caught (only on the thread itself), but if you're talking about waiting for the thread to finish, look at this class code here called ThreadTestARP that runs the above class on a thread...
public class ThreadTestARP
{
private TestARP _testARP = new TestARP();
private ManualResetEvent _mre = new ManualResetEvent(false);
public ThreadTestARP()
{
}
public TestARP ARPTest
{
get { return this._testARP; }
}
public void Run()
{
Thread t = new Thread(new ThreadStart(RunThread));
t.Start();
this._mre.WaitOne();
// Blocks here...
t.Join();
}
private void RunThread()
{
this._testARP.Run();
this._mre.Set();
}
}
Note how the ManualResetEvent _mre is used to signal to say in the context of the thread, "right, I am done, back to the creator..."
Why can't you cast to a Process object? You can still access some members of Process objects, such as ExitCode or ExitTime, that have terminated.
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx
How do I invoke a console application from my .NET application and capture all the output generated in the console?
(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
This is bit improvement over accepted answer from #mdb. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because ReadToEnd() doesn't work if you want to capture both error and regular output. It took me while to make this work because it actually also requires BeginxxxReadLine() calls after Start().
Asynchronous way:
using System.Diagnostics;
Process process = new Process();
void LaunchProcess()
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);
process.Exited += new System.EventHandler(process_Exited);
process.StartInfo.FileName = "some.exe";
process.StartInfo.Arguments = "param1 param2";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
//below line is optional if we want a blocking call
//process.WaitForExit();
}
void process_Exited(object sender, EventArgs e)
{
Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString()));
}
void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data + "\n");
}
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data + "\n");
}
Use ProcessStartInfo.RedirectStandardOutput to redirect the output when creating your console process.
Then you can use Process.StandardOutput to read the program output.
The second link has a sample code how to do it.
ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.
The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.
Also available as NuGet package.
Sample call to get full console output:
// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}
Sample with live feedback:
// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
var app = new ConsoleApp("ping", url);
app.ConsoleOutput += (o, args) =>
{
var match = regex.Match(args.Line);
if (match.Success)
{
var roundtripTime = match.Groups["time"].Value;
replyHandler(roundtripTime);
}
};
app.Run();
}
I've added a number of helper methods to the O2 Platform (Open Source project) which allow you easily script an interaction with another process via the console output and input (see http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs)
Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (this blog also contains details of how to consume the console output of new processes)
I made a reactive version that accepts callbacks for stdOut and StdErr.
onStdOut and onStdErr are called asynchronously,
as soon as data arrives (before the process exits).
public static Int32 RunProcess(String path,
String args,
Action<String> onStdOut = null,
Action<String> onStdErr = null)
{
var readStdOut = onStdOut != null;
var readStdErr = onStdErr != null;
var process = new Process
{
StartInfo =
{
FileName = path,
Arguments = args,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = readStdOut,
RedirectStandardError = readStdErr,
}
};
process.Start();
if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));
if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));
process.WaitForExit();
return process.ExitCode;
}
private static void ReadStream(TextReader textReader, Action<String> callback)
{
while (true)
{
var line = textReader.ReadLine();
if (line == null)
break;
callback(line);
}
}
Example usage
The following will run executable with args and print
stdOut in white
stdErr in red
to the console.
RunProcess(
executable,
args,
s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },
s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); }
);
From PythonTR - Python Programcıları Derneği, e-kitap, örnek:
Process p = new Process(); // Create new object
p.StartInfo.UseShellExecute = false; // Do not use shell
p.StartInfo.RedirectStandardOutput = true; // Redirect output
p.StartInfo.FileName = "c:\\python26\\python.exe"; // Path of our Python compiler
p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py"; // Path of the .py to be executed
Added process.StartInfo.**CreateNoWindow** = true; and timeout.
private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
using (Process process = new Process())
{
process.StartInfo.FileName = exeName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMilliseconds);
if (exited)
{
exitCode = process.ExitCode;
}
else
{
exitCode = -1;
}
}
}