C#中實(shí)現(xiàn)不同進(jìn)程(EXE)間通信的主流方案
C#中實(shí)現(xiàn)不同進(jìn)程(EXE)間通信的方案,7種主流技術(shù)及代碼實(shí)現(xiàn):
一、命名管道(Named Pipes)【推薦本地高效通信】
1. 服務(wù)端實(shí)現(xiàn)
using System.IO.Pipes;
using System.Text;
var server = new NamedPipeServerStream("TestPipe", PipeDirection.InOut);
server.WaitForConnection();
Console.WriteLine("客戶端已連接");
// 接收數(shù)據(jù)
byte[] buffer = new byte[256];
int bytesRead = server.Read(buffer, 0, buffer.Length);
string msg = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
Console.WriteLine($"收到消息:{msg}");
// 發(fā)送響應(yīng)
string response = "Hello from server!";
byte[] respBytes = Encoding.UTF8.GetBytes(response);
server.Write(respBytes, 0, respBytes.Length);
server.Close();
2. 客戶端實(shí)現(xiàn)
using System.IO.Pipes;
using System.Text;
var client = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut);
client.Connect();
Console.WriteLine("已連接到服務(wù)端");
// 發(fā)送數(shù)據(jù)
string message = "Hello from client!";
byte[] msgBytes = Encoding.UTF8.GetBytes(message);
client.Write(msgBytes, 0, msgBytes.Length);
// 接收響應(yīng)
buffer = new byte[256];
bytesRead = client.Read(buffer, 0, buffer.Length);
string resp = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
Console.WriteLine($"服務(wù)端響應(yīng):{resp}");
client.Close();
適用場(chǎng)景:本地雙向?qū)崟r(shí)通信,高性能數(shù)據(jù)傳輸
二、內(nèi)存映射文件(Memory-Mapped Files)【推薦大數(shù)據(jù)量共享】
1. 寫(xiě)入進(jìn)程
using System.IO.MemoryMappedFiles;
using System.Text;
using (var mmf = MemoryMappedFile.CreateOrOpen("SharedMemory", 1024))
using (var accessor = mmf.CreateViewAccessor())
{
string data = "共享內(nèi)存數(shù)據(jù)";
byte[] bytes = Encoding.UTF8.GetBytes(data);
accessor.WriteArray(0, bytes, 0, bytes.Length);
}
2. 讀取進(jìn)程
using System.IO.MemoryMappedFiles;
using System.Text;
using (var mmf = MemoryMappedFile.OpenExisting("SharedMemory"))
using (var accessor = mmf.CreateViewAccessor())
{
byte[] buffer = new byte[1024];
accessor.ReadArray(0, buffer, 0, buffer.Length);
string msg = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
Console.WriteLine($"讀取數(shù)據(jù):{msg}");
}
特點(diǎn):零拷貝傳輸,適合頻繁讀寫(xiě)的大數(shù)據(jù)場(chǎng)景
三、WCF服務(wù)【推薦復(fù)雜服務(wù)交互】
1. 服務(wù)端定義
[ServiceContract]
public interface IMyService
{
[OperationContract]
string ProcessData(string input);
}
public class MyService : IMyService
{
public string ProcessData(string input) => $"處理結(jié)果:{input.ToUpper()}";
}
// 啟動(dòng)服務(wù)
var host = new ServiceHost(typeof(MyService), new Uri("net.pipe://localhost"));
host.AddServiceEndpoint(typeof(IMyService), new NetNamedPipeBinding(), "MyService");
host.Open();
2. 客戶端調(diào)用
var factory = new ChannelFactory<IMyService>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/MyService"));
IMyService proxy = factory.CreateChannel();
string result = proxy.ProcessData("test data");
Console.WriteLine(result);
優(yōu)勢(shì):支持多種協(xié)議(TCP/HTTP),適合分布式系統(tǒng)
四、TCP套接字【推薦跨網(wǎng)絡(luò)通信】
1. 服務(wù)端
using System.Net.Sockets;
using System.Text;
var listener = new TcpListener(IPAddress.Any, 5000);
listener.Start();
using (var client = await listener.AcceptTcpClientAsync())
using (var stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
string response = "TCP響應(yīng)數(shù)據(jù)";
await stream.WriteAsync(Encoding.UTF8.GetBytes(response), 0, response.Length);
}
2. 客戶端
using System.Net.Sockets;
using System.Text;
var client = new TcpClient("127.0.0.1", 5000);
using (var stream = client.GetStream())
{
string msg = "Hello Server";
await stream.WriteAsync(Encoding.UTF8.GetBytes(msg), 0, msg.Length);
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string resp = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(resp);
}
特點(diǎn):支持跨網(wǎng)絡(luò)通信,靈活控制協(xié)議
五、消息隊(duì)列(MSMQ)【推薦異步可靠通信】
1. 發(fā)送消息
using System.Messaging;
var queue = new MessageQueue(@".\Private$\MyQueue");
queue.Send("異步消息內(nèi)容", MessageQueueTransactionType.Single);
2. 接收消息
var queue = new MessageQueue(@".\Private$\MyQueue");
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
queue.ReceiveCompleted += (s, e) => {
var msg = queue.EndReceive(e.AsyncResult);
Console.WriteLine($"收到消息:{msg.Body}");
};
queue.BeginReceive();
適用場(chǎng)景:需要可靠異步傳輸?shù)膱?chǎng)景
六、文件系統(tǒng)監(jiān)控【推薦簡(jiǎn)單同步場(chǎng)景】
1. 寫(xiě)入進(jìn)程
File.WriteAllText("shared.txt", "同步數(shù)據(jù):" + DateTime.Now);
2. 監(jiān)控進(jìn)程
var watcher = new FileSystemWatcher {
Path = ".",
Filter = "shared.txt",
NotifyFilter = NotifyFilters.LastWrite
};
watcher.Changed += (s, e) => {
string content = File.ReadAllText(e.FullPath);
Console.WriteLine($"文件更新:{content}");
};
watcher.EnableRaisingEvents = true;
特點(diǎn):實(shí)現(xiàn)簡(jiǎn)單,適合臨時(shí)數(shù)據(jù)同步
七、Windows API消息傳遞【推薦GUI應(yīng)用交互】
1. 發(fā)送消息(C#調(diào)用Win32 API)
[DllImport("User32.dll")]
static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
public struct COPYDATASTRUCT {
public int dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)] public string lpData;
}
// 發(fā)送消息示例
int hWnd = FindWindow(null, "目標(biāo)窗口標(biāo)題");
byte[] data = Encoding.Default.GetBytes("消息內(nèi)容");
int len = data.Length;
COPYDATASTRUCT cds = new COPYDATASTRUCT {
dwData = 100,
cbData = len + 1,
lpData = Encoding.Default.GetString(data)
};
SendMessage(hWnd, 0x004A, 0, ref cds);
2. 接收消息(目標(biāo)進(jìn)程)
protected override void WndProc(ref Message m) {
if (m.Msg == 0x004A) {
COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
textBox1.Text = cds.lpData;
}
base.WndProc(ref m);
}
適用場(chǎng)景:Windows窗體應(yīng)用間的直接交互
八、互斥體同步【推薦資源競(jìng)爭(zhēng)控制】
var mutex = new Mutex(false, "Global\\ProcessMutex");
// 進(jìn)程A
mutex.WaitOne();
try {
// 訪問(wèn)共享資源
} finally {
mutex.ReleaseMutex();
}
// 進(jìn)程B同理
作用:防止多進(jìn)程同時(shí)訪問(wèn)臨界區(qū)資源
參考代碼 c#進(jìn)程之間通信,c#exe 之間發(fā)消息,c#exe 相互通信 www.youwenfan.com/contentcsp/116346.html
選擇建議
| 場(chǎng)景 | 推薦方案 | 優(yōu)勢(shì) |
|---|---|---|
| 本地實(shí)時(shí)雙向通信 | 命名管道 | 高性能,低延遲 |
| 跨網(wǎng)絡(luò)通信 | TCP套接字/WCF | 支持遠(yuǎn)程,協(xié)議靈活 |
| 異步可靠傳輸 | MSMQ | 消息持久化,斷點(diǎn)續(xù)傳 |
| 簡(jiǎn)單數(shù)據(jù)同步 | 文件監(jiān)控 | 實(shí)現(xiàn)簡(jiǎn)單,無(wú)需復(fù)雜配置 |
| GUI應(yīng)用交互 | Win32消息傳遞 | 直接操作窗口控件 |
| 資源競(jìng)爭(zhēng)控制 | 互斥體 | 避免數(shù)據(jù)競(jìng)爭(zhēng) |
性能對(duì)比
| 方法 | 吞吐量 (MB/s) | 延遲 (ms) | 跨網(wǎng)絡(luò)支持 |
|---|---|---|---|
| 命名管道 | 120-200 | 0.1-1 | 否 |
| 內(nèi)存映射文件 | 500-800 | <0.01 | 否 |
| TCP套接字 | 80-150 | 1-5 | 是 |
| MSMQ | 10-30 | 50-200 | 是 |
調(diào)試技巧
- 管道調(diào)試:使用
Process Explorer查看命名管道狀態(tài) - 網(wǎng)絡(luò)抓包:Wireshark過(guò)濾
tcp.port == 5000分析TCP通信 - 內(nèi)存監(jiān)控:使用
VMMap工具觀察內(nèi)存映射文件使用情況
高級(jí)應(yīng)用
- 混合通信:結(jié)合TCP套接字(傳輸)+ 內(nèi)存映射文件(實(shí)時(shí)數(shù)據(jù))
- 加密傳輸:在TCP套接字中集成AES加密
- 協(xié)議擴(kuò)展:自定義二進(jìn)制協(xié)議提升傳輸效率
以上就是C#中實(shí)現(xiàn)不同進(jìn)程(EXE)間通信的主流方案的詳細(xì)內(nèi)容,更多關(guān)于C#實(shí)現(xiàn)不同進(jìn)程(EXE)間通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#/VB.NET?將Word與Excel文檔轉(zhuǎn)化為T(mén)ext
這篇文章主要介紹了C#/VB.NET?將Word與Excel文檔轉(zhuǎn)化為T(mén)ext,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08
C#程序最小化到托盤(pán)圖標(biāo)操作步驟與實(shí)現(xiàn)代碼
設(shè)置窗體屬性showinTask=false;加notifyicon控件notifyIcon1,為控件notifyIcon1的屬性Icon添加一個(gè)icon圖標(biāo);添加窗體最小化事件(首先需要添加事件引用)接下來(lái)介紹實(shí)現(xiàn)代碼,感興趣的朋友可以研究下2012-12-12
將c#編寫(xiě)的程序打包成應(yīng)用程序的實(shí)現(xiàn)步驟分享(安裝,卸載) 圖文
時(shí)常會(huì)寫(xiě)用c#一些程序,但如何將他們和photoshop一樣的大型軟件打成一個(gè)壓縮包,以便于發(fā)布.2011-12-12
C#中Override關(guān)鍵字和New關(guān)鍵字的用法詳解
這篇文章主要介紹了C#中Override關(guān)鍵字和New關(guān)鍵字的用法,需要的朋友可以參考下2016-01-01

