【发布时间】:2014-11-04 07:27:48
【问题描述】:
我有一个控制台 c# 应用程序(本机消息传递应用程序),它通过命名管道连接到 winform。控制台应用程序是与 chrome 连接的本机消息应用程序。 Winform 将命令发送到控制台应用程序以开始读取标准输入流以获取消息到 chrome 并将其发送到 winfrom。 我不知道如何保持控制台应用程序处于活动状态,以便它可以等待附加的事件以从 winform 获取命令并读取标准输入流。?
这是我的主要功能。
static void Main(string[] args)
{
StartChannel();
}
这是从命名管道获取消息的事件处理程序
public void StartChannel()
{
_pipeServer = new PipeServer();
_pipeServer.PipeMessage += new DelegateMessage(PipesMessageHandler);
_pipeServer.Listen(AppConstant.IPC_ConsoleReaderPipe);
}
private void PipesMessageHandler(string message)
{
if(message ="Start")
StartListener();
}
**这是我的问题中心。此处执行 StartListener 后,控制台应用程序关闭。我怎样才能让它在一个单独的线程中运行。这样它就不会阻塞 NamedPipe 通信**
private static void StartListener()
{
wtoken = new CancellationTokenSource();
readInputStream = Task.Factory.StartNew(() =>
{
wtoken.Token.ThrowIfCancellationRequested();
while (true)
{
if (wtoken.Token.IsCancellationRequested)
{
wtoken.Token.ThrowIfCancellationRequested();
}
else
{
OpenStandardStreamIn();
}
}
}, wtoken.Token
);
}
}
public static void OpenStandardStreamIn()
{
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
Console.Write(input);
}
【问题讨论】:
-
@Alex: Console.ReadLine 在读取 Console.OpenStandardInput() 的情况下将不起作用;在 OpenStandardStreamIn() 中; .也许我也应该粘贴代码。查看我的编辑。
-
是的,刚刚看到您的评论。我不知道:)
-
@Alex:没有问题。 :)
-
那么,这个控制台应用程序什么时候应该退出?对事件的任何等待操作都可以使其保持活动状态。如果要从另一个进程中停止此类程序,请使用命名事件。如果管道发生错误,您也可以设置此事件。
-
@AlexFarber : 谢谢,我会试试 Alex 并告诉你
标签: c# .net winforms console-application