日期:2014-05-17 浏览次数:21086 次
最近在做一个应用程序,涉及到两个应用程序之间的通讯,就想到了用C#的命名管道的方式来实现,经过一番小折腾,总算实现了,现把一些主题的代码粘贴出来与大家分享:
管道通讯会涉及到client端和Server端,Client端的主要代码:
需要引用命名空间:using System.IO.Pipes;
Thread pipeThread = new Thread(new ThreadStart(SendData));
pipeThread.IsBackground = true;
pipeThread.Start();
private void SendData()
{
try
{
_pipeClient = new NamedPipeClientStream(".","closePipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
_pipeClient.Connect();
StreamWriter sw = new StreamWriter(_pipeClient);
sw.WriteLine("Exit");
sw.Flush();
Thread.Sleep(1000);
sw.Close();
}
catch (Exception ex)
{
Log.WriteLog(ex.Message);
}
}
Sever端的代码:
Thread receiveDataThread = new Thread(new ThreadStart(ReceiveDataFromClient));
receiveDataThread.IsBackground = true;
receiveDataThread.Start();
private void ReceiveDataFromClient()
{
while (true)
{
try
{
_pipeServer = new NamedPipeServerStream("closePipe", PipeDirection.InOut, 2);
_pipeServer.WaitForConnection(); //Waiting
StreamReader sr = new StreamReader(_pipeServer);
string recData = sr.ReadLine();
if (recData == "Exit")
{
Log.WriteLog("Pipe Exit.", _logFile);
ExitApplication();
}
Thread.Sleep(1000);
sr.Close();
}
catch (Exception ex)
{
Log.WriteLog(ex.Message, _logFile);
}
}
}
这个例子只是Client与Sever端连接之后,给server端发消息,使其关闭的简单功能,也可以进行消息的回传。
这里需要注意的是,开启管道监听和管道连接最好是在线程中处理,否则主程序会卡死(No Responding)。
还有就是线程要设置为后台线程,否则程序退出后,在任务管理器中还会存在,不能完全退出。