如何用C#实现异步重定向控制台APP到其他APP [英] How to realize asynchrony re-direction Console APP into the othe APP with C#
本文介绍了如何用C#实现异步重定向控制台APP到其他APP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HI朋友:
这几天,我正在做一个关于将控制台应用程序重定向到另一个应用程序的练习,但是,我没有解决一个问题,总是产生死锁定位ReadToEnd(),所以我认为使用异步方法,但这对我来说不成功,我希望你能帮我解决问题。详情如下:
需要重新定向APP:
static void Main( string [] args)
{
int cout = 0 ;
cout ++;
Console.WriteLine( 从EXE成功输入一个字符串!);
Console.WriteLine(cout.ToString());
Console.WriteLine( 成功!退出!);
Console.Read();
}
另一个应用程序:
类程序
{
/// < 摘要 >
///重定向流类别Asynch
/// < / summary >
公共类ReDirectionStreamAsynch
{
#region字段
/// < 摘要 >
/// System.Diagnostics.Process
/// < / summary >
private Process p = null;
/// < 摘要 >
///重定向EXE路径
/// < / summary >
private string ExePath = string.Empty;
/// < 摘要 >
///从其他EXE输出流
/// < / summary >
private StreamReader StreamR;
/// < 摘要 >
///从其他EXE输出错误流
/// < / summary >
private StreamReader StreamErrorR;
/// < 摘要 >
///将流输入到其他EXE
/// < / summary >
private StreamWriter StreamW;
#endregion
#region构造函数
/// < 摘要 >
///构造函数
/// < / summary >
public ReDirectionStreamAsynch(string ExePathParameter)
{
if(!string.IsNullOrEmpty(ExePathParameter))
{
ExePath = ExePathParameter;
//初始化过程对象
p = new Process();
}
else
{
抛出新的InvalidDataException(EXE文件路径不能为空或空!);
}
}
#endregion
#region private delegate
/// < 摘要 >
/// StreamReader
/// < / summary >
private delegate int AsyncRead(IAsyncResult ar);
/// < 摘要 >
/// StreamWriter
/// < /摘要 >
private delegate int AsyncWrite(IAsyncResult ar);
#endregion
#region私人功能
/// < < span class =code-leadattribute>摘要 >
///从StreamReader读取infor(StandardOutput)
// / < / summary >
private int Read(IAsyncResult ar)
{
int result;
字符串输出;
try
{
output = StreamR.ReadToEnd();
Console.WriteLine(输出);
result = 1;
}
catch
{
result = 0;
}
返回结果;
}
/// < 摘要 >
///将信息写入StreamWriter(StandardInput)
/// < / summary >
private void Write(IAsyncResult ar)
{
string input = Console.ReadLine();
StreamW.WriteLine(输入);
AsyncRead Aread =(AsyncRead)ar.AsyncState;
Console.WriteLine(Read async finished:+(Aread.EndInvoke(ar)));
}
private void PostAsync()
{
AsyncRead Aread = new AsyncRead(Read);
Aread.BeginInvoke(null,new AsyncCallback(Write),Aread);
}
//公共覆盖void EndRead(IAsyncResult asyncResult)
// {
// base.EndWrite(asyncResult);
//}
//公共覆盖void EndWrite(IAsyncResult asyncResult)
// {
// base.EndWrite(asyncResult);
//}
#endregion
/// < 摘要 >
///开始执行重定向,这是默认执行条目。
///您可以手动设置一些有关Process对象的参数,然后执行它。
/// < / summary > ;
/// < 返回 > < / returns >
public StringBuilder BeginExeRedirection()
{
StringBuilder log = null;
// Destination Exe App
this.p.StartInfo.FileName = ExePath;
this.p.StartInfo.UseShellExecute = false;
this.p.StartInfo.RedirectStandardOutput = true;
this.p.StartInfo.RedirectStandardInput = true;
this.p.StartInfo.RedirectStandardError = true;
this.p.StartInfo.CreateNoWindow = true;
//p.OutputDataReceived + = new DataReceivedEventHandler(SortOutputHandler);
尝试
{
this.p.StandardInput.AutoFlush = true;
}
catch(例外e)
{
Console.WriteLine(AutoFlush+ e.Message);
}
this.p.Start();
StreamR = p.StandardOutput;
StreamErrorR = p.StandardError;
StreamW = p.StandardInput;
this.PostAsync();
this.p.WaitForExit();
this.StreamR.Dispose();
this.p.Dispose();
this.StreamW.Close();
this.StreamR.Close();
this.StreamErrorR.Close();
返回日志;
}
}
解决方案
您的代码示例中没有任何内容可以查看 - 请参阅我的评论问题。
问题本身非常简单;不要试图让事情如此复杂。请阅读有关输出的重定向的信息。例如,请参阅此MSDN文章中的代码示例: http:// msdn。 microsoft.com/en-us/library/vstudio/system.diagnostics.process.standardoutput [ ^ ]。
-SA
HI friends:
For these days, I am doing a practice about re-direct a console app into the other app, but, I don't resolve a problem that always produce dead lock locating ReadToEnd(), So I think to use asynchronous method, but this is not success for me, I hope you can help me to resolve the problem. Detail is below:
Need to be re-direction APP:
static void Main(string[] args)
{
int cout = 0;
cout++;
Console.WriteLine("Input a string from EXE success!");
Console.WriteLine(cout.ToString());
Console.WriteLine("Success! Exit!");
Console.Read();
}
The other App:
class Program
{
/// <summary>
/// Re-direction Stream Class Asynch
/// </summary>
public class ReDirectionStreamAsynch
{
#region Field
/// <summary>
/// System.Diagnostics.Process
/// </summary>
private Process p = null;
/// <summary>
/// Re-direction EXE path
/// </summary>
private string ExePath = string.Empty;
/// <summary>
/// Output a stream from the other EXE
/// </summary>
private StreamReader StreamR;
/// <summary>
/// Output a error stream from the other EXE
/// </summary>
private StreamReader StreamErrorR;
/// <summary>
/// Input a stream into the other EXE
/// </summary>
private StreamWriter StreamW;
#endregion
# region Constructor
/// <summary>
/// Constructor
/// </summary>
public ReDirectionStreamAsynch(string ExePathParameter)
{
if (!string.IsNullOrEmpty(ExePathParameter))
{
ExePath = ExePathParameter;
// Initialize Process object
p = new Process();
}
else
{
throw new InvalidDataException("The EXE file Path cannot be Null or Empty!");
}
}
# endregion
# region private delegate
/// <summary>
/// StreamReader
/// </summary>
private delegate int AsyncRead(IAsyncResult ar);
/// <summary>
/// StreamWriter
/// </summary>
private delegate int AsyncWrite(IAsyncResult ar);
#endregion
# region Private Function
/// <summary>
/// Read infor from StreamReader(StandardOutput)
/// </summary>
private int Read(IAsyncResult ar)
{
int result;
string output;
try
{
output = StreamR.ReadToEnd();
Console.WriteLine(output);
result = 1;
}
catch
{
result = 0;
}
return result;
}
/// <summary>
/// Write infor into StreamWriter(StandardInput)
/// </summary>
private void Write(IAsyncResult ar)
{
string input = Console.ReadLine();
StreamW.WriteLine(input);
AsyncRead Aread = (AsyncRead)ar.AsyncState;
Console.WriteLine("Read async finished: " + (Aread.EndInvoke(ar)));
}
private void PostAsync()
{
AsyncRead Aread = new AsyncRead(Read);
Aread.BeginInvoke(null, new AsyncCallback(Write), Aread);
}
//public override void EndRead(IAsyncResult asyncResult)
//{
// base.EndWrite(asyncResult);
//}
//public override void EndWrite(IAsyncResult asyncResult)
//{
// base.EndWrite(asyncResult);
//}
# endregion
/// <summary>
/// Begin to execute Re-direction, this is default execution entry.
/// You may set some parameter about Process object manually, and them executing it.
/// </summary>
/// <returns></returns>
public StringBuilder BeginExeRedirection()
{
StringBuilder log = null;
// Destination Exe App
this.p.StartInfo.FileName = ExePath;
this.p.StartInfo.UseShellExecute = false;
this.p.StartInfo.RedirectStandardOutput = true;
this.p.StartInfo.RedirectStandardInput = true;
this.p.StartInfo.RedirectStandardError = true;
this.p.StartInfo.CreateNoWindow = true;
//p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
try
{
this.p.StandardInput.AutoFlush = true;
}
catch(Exception e)
{
Console.WriteLine("AutoFlush"+e.Message);
}
this.p.Start();
StreamR = p.StandardOutput;
StreamErrorR = p.StandardError;
StreamW = p.StandardInput;
this.PostAsync();
this.p.WaitForExit();
this.StreamR.Dispose();
this.p.Dispose();
this.StreamW.Close();
this.StreamR.Close();
this.StreamErrorR.Close();
return log;
}
}
解决方案
There is nothing to look at in your code sample — please see my comments to the question.
The problem itself is extremely simple; don't try to make thing so complex. Please read about re-direction of output. See, for example, code sample in this MSDN article: http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.process.standardoutput[^].
—SA
这篇关于如何用C#实现异步重定向控制台APP到其他APP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文