C# 程序间通信之管道通信

前言:两个不同的Winform程序之间,有时候是需要相互通讯获取数据的。之前的文章中,也有写过类似的功能,同时也介绍了几种实现方式;只不过在那一篇中主要是用Windows Api来实现,也就是使用SendMessage函数来发送句柄消息。

在这里,我们使用另一种方式,即使用管道通信再来实现一次。这种方式的实现代码比使用SendMessage还要简单一些,而且兼容性也好很多,同时可扩展性也比较高,以下是一个简单的使用例子。.

  1. 分别创建两个Winform程序,一个用来接收,一个用来发送。

  2. 在两个程序中分别需要引入以下命名空间

using System.IO;using System.IO.Pipes;

3. 发送端的代码,比较简单,在按钮事件中直接处理发送即可


 

private void btn_send_Click(object sender, EventArgs e) { try { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "Pipeline", PipeDirection.Out)) { pipeClient.Connect(3000); using (StreamWriter sw = new StreamWriter(pipeClient)) { sw.WriteLine(textBox1.Text); sw.Flush(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }

4. 接收端的代码,在程序启动后就开始使用死循环进行接收,为了不让程序直接卡死,所以这里要写在异步方法中。


 

private void Form1_Load(object sender, EventArgs e) { Task.Run(() => { while (true) { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("Pipeline", PipeDirection.In, 1)) { pipeServer.WaitForConnection(); using (StreamReader sr = new StreamReader(pipeServer)) { this.Invoke(new Action(() => { label1.Text = sr.ReadToEnd(); })); } } } }); }

5. 结束

实现效果:

C# 程序间通信之管道通信