110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
public class RunConsole
{
#region 私有变量
private Process p;
private Thread t;
private object threadLock = new object();
string filename = String.Empty;
string arg = String.Empty;
string details = String.Empty;
AutoResetEvent resetEvent = new AutoResetEvent(false);
ManualResetEvent pauseEvent = new ManualResetEvent(true);
public AutoResetEvent thisEvent = new AutoResetEvent(false);
#endregion
public RunConsole(string file, string paras, ref string details)
{
filename = file;
arg = paras;
this.details = details;
}
public void Stop()
{
t.Abort();
if (!p.HasExited) p.Kill();
}
public void Run()
{
t = new Thread(new ThreadStart(this.ExecuteCMD));
t.Start();
resetEvent.WaitOne();
Thread.Sleep(1000);
thisEvent.Set();
}
private void ExecuteCMD()
{
p = new Process();
try
{
p.StartInfo = new ProcessStartInfo();
p.StartInfo.FileName = filename;
p.StartInfo.Arguments = arg;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
catch
{ ;}
finally
{
resetEvent.Set();
t.Abort();
t = null;
if (!p.HasExited) p.Kill();
}
}
void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
lock (threadLock)
{
details += e.Data + "\r\n";
}
//throw new NotImplementedException();
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
lock (threadLock)
{
details += e.Data + "\r\n";
}
//throw new NotImplementedException();
}
}
string output = String.Empty;
RunConsole runConsole = new RunConsole(fileName, paras, ref output);
runConsole.Run();