首先,我已经阅读了所有相关主题,他们提出了一般性的想法,但实施对我不起作用:
Send strings from one console application to another
How to send input to the console as if the user is typing?
Sending input/getting output from a console application (C#/WinForms)
我有一个控制台应用程序,它在后台执行一些操作,直到请求取消。典型的使用场景是:
1)执行申请
2)输入输入数据
3)发出开始命令
4)经过一段时间后,输入停止命令
5)退出申请
子申请Program.cs
:
static void Main()
{
Console.WriteLine("Enter input parameter : ");
var inputParameter = Console.ReadLine();
Console.WriteLine("Entered : " + inputParameter);
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Stopping actions");
return;
}
// Simulating some actions
Console.Write("*");
}
}, token);
if (Console.ReadKey().KeyChar == 'c')
{
tokenSource.Cancel();
Console.WriteLine("Stop command");
}
Console.WriteLine("Finished");
Console.ReadLine();
}
我正在寻找的是某种控制此应用程序的主机实用程序 - 在每个实例上生成多个实例并执行所需的用户操作。
主持人申请Program.cs
:
static void Main()
{
const string exe = "Child.exe";
var exePath = System.IO.Path.GetFullPath(exe);
var startInfo = new ProcessStartInfo(exePath)
{
RedirectStandardOutput = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
WindowStyle = ProcessWindowStyle.Maximized,
CreateNoWindow = true,
UseShellExecute = false
};
var childProcess = new Process { StartInfo = startInfo };
childProcess.OutputDataReceived += readProcess_OutputDataReceived;
childProcess.Start();
childProcess.BeginOutputReadLine();
Console.WriteLine("Waiting 5s for child process to start...");
Thread.Sleep(5000);
Console.WriteLine("Enter input");
var msg = Console.ReadLine();
// Sending input parameter
childProcess.StandardInput.WriteLine(msg);
// Sending start command aka any key
childProcess.StandardInput.Write("s");
// Wait 5s while child application is working
Thread.Sleep(5000);
// Issue stop command
childProcess.StandardInput.Write("c");
// Wait for child application to stop
Thread.Sleep(20000);
childProcess.WaitForExit();
Console.WriteLine("Batch finished");
Console.ReadLine();
}
当我运行此工具时,在第一次输入后,它会因“已停止工作”错误而崩溃,并提示将内存转储发送给Microsoft。 VS中的输出窗口没有例外。
猜测这个问题发生在应用程序之间的某个地方,可能是因为输出流缓冲区溢出(子应用程序每秒都写了很多星星模仿实际输出,这可能是巨大的),我还不知道如何解决它。我真的不需要将子输出传递给主机(只向子节点发送start-stop命令),但注释RedirectStandardOutput和OutputDataReceived并不能解决这个问题。任何想法如何使这项工作?
答案 0 :(得分:8)
我建议使用NamedPipeServerStream
和NamedPipeClientStream
,它允许您打开一个流,该流将在给定计算机上的进程之间进行通信。
首先,这将创建一个管道服务器流并等待某人连接到它:
var stream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut);
stream.WaitForConnection();
return stream;
然后,这将连接到该流(来自您的其他进程),允许您向任一方向读/写:
var stream = new NamedPipeClientStream(".", this.PipeName, PipeDirection.InOut);
stream.Connect(100);
return stream;
答案 1 :(得分:0)
另一种选择是使用MSMQ,你可以找到一个好的教程here
答案 2 :(得分:0)
我建议您查看使用.NET 4中的内存映射文件 http://blogs.msdn.com/b/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx
快速而有效。