我有一个控制台c#应用程序(本机消息传递应用程序),它通过命名管道连接到winform。 console app是一个与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);
}
答案 0 :(得分:1)
您应该尝试使用AutoResetEvent
- 请参阅http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx
这样,您的主线程在侦听器线程上等待,直到事件设置为止,并且仅在此之后终止
如果您使用的是.NET 4.5,则应使用async
和await
个关键字以及Task.Run()
- &gt;见http://msdn.microsoft.com/en-us/library/hh191443.aspx